I have a Laravel route that I want to handle differently depending on whether the user is logged in or not. If the user is not logged in, I want to retrieve only 5 records (limit 5) in the controller. If the user is logged in, I want to retrieve all the records.
Here is my current route:
Route::get('/test', 'TestApiController@index');
When I set middleware(‘auth:sanctum’) for my Route, the response will be 401 Unauthorized, but I want to get limited records for this situation instead. How can I modify the route and the controller to achieve this? Also, how do I check if the user is logged in?
Here is my current controller code:
class TestApiController extends Controller
{
public function index()
{
if (auth()->check()) {
$data = Test::all();
} else {
$data = Test::limit(5)->get();
}
return response()->json($data);
}
}
I think I need to get the authentication parameter from the request header to check if the user is logged in:
$request->header('Authorization')
How can I modify my code to achieve the desired functionality? Thank you.
I try when or middlewareIf and middleware(function ($request, $next),
but they are not working..
2
Answers
Looks like you are mixing some concepts there.
Your route looks like an API route, which uses ‘api’ guard instead of web. When you call for
auth()->check()
its getting the ‘web’ guard.Knowing this, your controller should look like this:
You can read more in the Laravel authentication documentation.
I noticed that your code is authorized by Sanctum
Route:
Controller:
Solution #1:
Solution #2: