简体   繁体   中英

Use Auth facade in API routes (Laravel 8)

I am looking to use Auth::user() in the CompanyController sitting in the api.php route file in Laravel 8 . Like

Route::get('team', [CompanyController::class, 'index']);

But if I do so, I won't be able to access Auth in the following code in the CompanyController file.

use Illuminate\Support\Facades\Auth;

public function index(Request $request)
    {

        /**
         * Role 1 => admin, 2 => hr, 3=> member
         */

        if (Auth::user()->role <= 2) {

            return ['company' => Auth::user()->company, 'team' => Auth::user()->company->users];
        }
    }

So what I have done now to achieve what I need is prefix api to the routes sitting in the web.php route file instead.

Route::prefix('api')->group(function () {
    Route::get('team', [CompanyController::class, 'index']);
}

After googling around, I am more or less aware that Laravel Sanctum may solve the issue, and it's happened because of the Token driver used in the Api routes. But I'm wondering if there is any easy alternative solution for this. It looks like it would take a while to customise the login page with Sanctum.

What I want is still to take advantage of the initial login page set up with the Breeze starter kit. At the same time, after the user logs in, they can get access to Auth.

if (Auth::user()->role <= 2) {

Here you assume that the user is authenticated and you need to put this route with the authentication middleware. For example:

Route::get('team', [CompanyController::class, 'index'])->middleware('auth');

If you will use Laravel Sanctum, you need to protect routes (only if really needed)

Route::get('team', [CompanyController::class, 'index'])->middleware('auth:sanctum');

Documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM