You mean in api.php? By default those routes does not have sessions and therefor no user. Are you using sanctum?
Get user info in api route/controller method
I'm trying to get the current user instance in an api route/controller method. Using auth()->user(); returns null, however. How do I get the current user instance?
Complete controller method:
return Favorite::where('user_id', auth()->user()->id)->get();
@Sinnbeck Yes, I'm using sanctum. Is there a way to pass the session to those routes, or should I just use web.php routes?
@Sinnbeck With sanctum, it's yet possible to retrieve the connected user.
Route::middleware('auth:sanctum')->group(function () {
Route::get('user', function (Request $request) {
return $request->user();
});
});
@vincent15000 I'm trying to do it from my controller, which is being accessed through a route in api.php. I think I'm using it wrong though, and need to setup token based auth for my api routes.
@pfigdev did you try the suggestion by @vincent15000 ?
return Favorite::where('user_id', $request->user()->id)->get();
Did you remember to add the middleware as described in the docs? (I assume this is a SPA)
https://laravel.com/docs/9.x/sanctum#installation
Next, if you plan to utilize Sanctum to authenticate an SPA, you should add Sanctum's middleware to your api middleware group within your application's app/Http/Kernel.php file:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
@pfigdev I don't know if is recommended or not , but you can add API to the configuration file https://github.com/laravel/sanctum/blob/2.x/config/sanctum.php#L36
'guard' => ['web','api'],
@sos99 Thanks for the suggestion. I think I should stick to best practices as I'm too early in my development career to start bad habits. How would you go about protecting api.php routes, and only pulling data from the database based on the current user's id?
@pfigdev If you are using Sanctum, you should protect your API routes like this.
Route::middleware('auth:sanctum')->group(function () {
// your API routes
});
Then if you want to bind the new data with the current connected user, you only need to retrieve the connected user via the request.
public function list(Request $request)
{
$connected_user = $request->user();
}
Then you have access to all the needed informations of the connected user, for example his id, his name, ...
auth()->user() should also work, but I haven't tested in API mode.
hey you can return the value like this it is work for me:
return ["Favorites" => Favorite::where('user_id', auth()->user()->id)->get()];
if your 'api' requests are coming from a browser just simplify things by using web routes
if you are set on using api routes (stateless) then you have to send the sanctum token with every request
@vincent15000 is true but he tries to get auth from API route
https://laravel.com/docs/9.x/sanctum#how-it-works
For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. Typically, Sanctum utilizes Laravel's web authentication guard to accomplish this. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.
SPA = cookies
API = tokens
@sos99 Me too and it works ;).
$request->user()
@vincent15000 also from the docs (I add the boldface)
For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. Typically, Sanctum utilizes Laravel's web authentication guard to accomplish this. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.
but routes in the api file don't use web middleware
so maybe you changed something in middleware-group or other configuration files
I don't think is the right way to solve the problem of this issue
@Snapey Ok I meant inside the controllers but not in the routes.
and some secret
use Illuminate\Support\Facades\Auth;
//...
Auth::id()
is enough :)
source:
https://laravel.com/docs/9.x/authentication#retrieving-the-authenticated-user
thank you for all the suggestions, I have a few different things to try out now. I'm going to try @snapey's suggestion of using web routes to simplify things, as I dont want to use api routes if it's not best practice for this purpose. i'm going to try using @vincent15000's suggestions as well just to see if I can get it working. i'll report back once i'm done playing around. thanks again everyone.
Please or to participate in this conversation.