I want to use my show method in controller between if statement while declaring route:
Route::get('/leave', function() {
if(Auth::user()->admin)
{
'uses' => 'TimeController@show'
}
else {
return "not found";
}
})->name('admin-time');
but the uses
that I define it doesn't work! and I know it shouldn't works.
Route:
Route::get('/leave', 'TimeController@show')->name('admin-time');
Controller:
public function show()
{
if(!Auth::user()->admin)
{
return abort(404);
}
// your code.
}
Remember: Do not use closure based routes. It prevents you from
route:cache
.
For authenticating like this you should use either a middleware: https://laravel.com/docs/5.6/middleware
For example, protect the route by wrapping it in a custom middleware auth:admin
:
Route::middleware('auth:admin')->group(function () {
Route::get('/leave', ['uses' => 'TimeController@show'])->name('admin-time');
});
Or use a custom Request: https://laravel.com/docs/5.6/requests
For example, keep your route as:
Route::get('/leave', ['uses' => 'TimeController@show'])->name('admin-time');
In your TimeController
your show
method will have your custom Request
that you can generate using php artisan make:request MyCustomRequest
public function show(MyCustomRequest $request) {
...
}
And in your MyCustomRequest
you can add this to the authorize()
method:
public function authorize()
{
if (Auth::user()->admin) {
return true;
}
return false;
}