简体   繁体   中英

How to access model method based on api auth in laravel 5.6?

I have user cars having many to many relation between users and cars. I am using passport and everthing is working properly (Sign-in, Sign-up etc) In my I have a method like below in Users Model

public function cars()
    { 
        return $this->belongsToMany(Car::class, 'users_cars', 'user_id', 'car_id');
    }

I also have API auth routes which is working fine

Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', 'AuthController@login');
    Route::post('signup', 'AuthController@signup');

    Route::group([
      'middleware' => 'auth:api'
    ], function() {
        Route::get('logout', 'AuthController@logout');
        Route::get('user', 'AuthController@user');
        Route::get('car-list','CarController@carList');
    });
});

And in CarController I am trying to get user cars based on auth login user_id as like below

public function carList(){
    $User = new User();
    return new CarResource($User->cars());
}

I am also using API resource for API's

use App\Http\Resources\Car as CarResource;

But it does not working so can someone kindly guide me how to fix the issue. I would appreciate, thank you so much.

In the CarController you are instantiating a new User object. They are never going to have any cars. If you want to get all the cars that the user who is logged in, you will need to do something like the following:

public function carList(){
    $User = User::with('cars')->findOrFail(Auth::id());
    return new CarResource($User->cars);
}

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