I follow this tutorial : https://www.youtube.com/watch?v=kmJYVhG6UzM Currently I can check in my blade if user is a admin or not like this:
{{ Auth::user()->roles->toArray()[0]['role'] }}
HI ADMIN
@endif
How can I make my route only available for admin user?
You need to create a middleware for your route.
Use:
php artisan make:middleware AdminMiddleware
.You will find in your middleware folder a new file with this name.
Put your logic in your middleware, e.g.
Once you have done your logic in your middleware, you can either call it in the route or make the middleware apply to all routes.
If you want to add it to all routes, go to
Kernel.php
and add it to the$middleware
array, e.g.If you want to add it to specific routes only, add it to the
$routeMiddleware
variable and add the alias to the route. E.g.You can then add it to a route, as a filter, e.g.
For additional info visit the docs:
http://laravel.com/docs/master/middleware
EDIT
An improvement on this would be to use variadic functions which was introduced in PHP 5.6
http://php.net/manual/en/migration56.new-features.php
Instead of having to make a middleware for each permission set you can do the following
PermissionMiddleware
Notice the ...$permitted_roles
You can now specify as many roles as required for one middleware rather than creating multiple by using middleware parameters
Docs https://laravel.com/docs/5.3/middleware#middleware-parameters
use middleware and check for admin user.
now create middleware and validate admin user.
Let's assume you have a column in your users table with
isAdmin
name which has a default value of 0 (false)You can give special access using middleware in laravel like you give access to logged in users using
auth
middleware in laravel. Now you need to create a middleware using the command :In your Kernel.php you need to add this line to
protected $routeMiddleware
In your middleware folder you have the
AdminMiddleware
file. In that you need to put your logic In this case this is how it might look like depending upon youNow in your route you have to pass the url using this middleware Here is how it might look like