I'm trying to make one route in laravel which can have a user if it is logged-in but can still work if not.
In my case I have a table called "venues" and a "user" that can have a venue as his favourite.
So these are my routes:
Route::group(['middleware' => ['cors', 'bindings', 'auth:api']], function () {
Route::match(['GET', 'OPTIONS'], 'venue/{venue}', 'VenuesController@getVenue')->name('venue')->where('venue', '[0-9]+');
});
Route::group(['middleware' => ['cors', 'bindings', 'api'], 'namespace' => 'Api'], function () {
Route::match(['GET', 'OPTIONS'], 'venue/{venue}', 'VenuesController@getVenue')->name('venue')->where('venue', '[0-9]+');
});
Now I noticed that Auth::user();
is only available in the route with the middleware with 'auth:api'
but I also want it to get the venue if the user is not logged in. And using both groups doesn't work this way.
My Venue model looks like this:
class Venue extends Model
{
protected $appends = [
'favourite',
];
public function users()
{
return $this->belongsToMany('App\Models\User', 'venue_user');
}
public function getFavouriteAttribute()
{
$user = Auth::user();
$isFav = false;
if ($user) {
if ($user->venues) {
foreach ($user->venues as $item) {
if ($item->id === $this->id) {
$isFav = true;
}
}
}
}
return $isFav;
}
}
There must be a better way to do this.
I hope someone can help me out.
Ok I finally found the answer to my own question. Apparently the right way to get the current of Passport is by doing:
$user = auth()->guard('api')->user();
Auth::user()
is only available in routes with a middlewhere of 'auth:api'
but this one is available everywhere if I say so correctly.
Feel free to correct me if I'm wrong :)