I am new to laravel 5.8 , am not able to use Auth
in api controllers, below are the details :
users
to User
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'User';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'firstName', 'lastName', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Did not change anything in auth.php
<?php
return
['defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
My question : How can I make Auth::check() work in this controller and get user id. This returns Not logged
<?php
namespace App\Http\Controllers\api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
use Response;
use Auth;
class AccountsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
$userID = Auth::id();
if (Auth::check()) {
return "User logged , user_id : ".$userID ;
}else{
return "Not logged"; //It is returning this
}
}
}
I have tried several answers of similar questions ( Q1 Q2 ) but it didn't work.
There would be no logged in user if using the API routes. Authentication for API's are done by tokens, you can read about it in the Laravel docs.
The session middleware is not called unless you use the web routes so the session is not started and therefore its not possible to use Auth.
What is it your trying to achieve as its not normal to use Auth with API routes.
Use can try this for setting auth user in the session. This will set the user after authentication and set Auth::user().
Auth::attempt(['email' => request('email'), 'password' => request('password')])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With