Search

LaravelMiddleware's Tags

Laravel 5.5 - Login With Only Mobile Number Using Laravel Custom Auth
Today, we are share with you how to modify laravel bydefault authentication and make it custom as per our requirement. in this totorials we are modify laravel authentication sysstem and make "how to login with only mobile number in laravel application using laravel custom authentication". but you also can modify as per your requirement. Laravel provide bydefault authentication system on users table's email and password fields and it very helpfull for us. but sometime we want to change laravel authentication and make is as per our requirment. Ex. we want username or password, we want mobile number and password and sometime we want only mobile number for authentication and not extra needed. so, how to built laravel custom authentication? we are share here with very simple example. if you fallow all step then you can change laravel auth and set your custom auth as per your choice. it is very easy. Create Laravel New Project First, we are create one new fresh laravel project run by following command. if you already have laravel project and you want implement custom auth your exist laravel application. so, this step skeep and move on next. composer create-project --prefer-dist laravel/laravel blog After installation please setup your database in .env file Create Laravel Auth Next, Generate laravel bydefault auth run by following command php artisan make:auth Run Laravel Migration Befor run laravel migration please add one extra mobile_no field in user table migration open it and add like that. Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('mobile_no')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); Next, then after run laravel migration using following command php artisan migrate Change in RedirectIfAuthenticated Next, now we are need some changes in RedirectIfAuthenticated middleware. so, open your app/Http/Middleware/RedirectIfAuthenticated.php file and make change like that. namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class RedirectIfAuthenticated { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { if (Auth::check()) { return redirect('/home'); } return $next($request); } } [ADDCODE] Overwrite login() method Next, we are need to overwrite login() method. so, open your app/Http/Controllers/Auth/LoginController.php file and make some change following way. namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use App\Http\Requests; use App\User; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); $this->user = new User; } public function login(Request $request) { // Check validation $this->validate($request, [ 'mobile_no' => 'required|regex:/[0-9]{10}/|digits:10', ]); // Get user record $user = User::where('mobile_no', $request->get('mobile_no'))->first(); // Check Condition Mobile No. Found or Not if($request->get('mobile_no') != $user->mobile_no) { \Session::put('errors', 'Your mobile number not match in our system..!!'); return back(); } // Set Auth Details \Auth::login($user); // Redirect home page return redirect()->route('home'); } } Change In Login Blade Next, open your resources/views/auth/login.blade.php file and make changes this way. @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Login</div> <div class="panel-body"> <form class="form-horizontal" method="POST" action="{{ route('login') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('mobile_no') ? ' has-error' : '' }}"> <label for="mobile_no" class="col-md-4 control-label">Enter Mobile No.</label> <div class="col-md-6"> <input id="mobile_no" type="text" class="form-control" name="mobile_no" value="{{ old('mobile_no') }}" required autofocus> @if ($errors->has('mobile_no')) <span class="help-block"> <strong>{{ $errors->first('mobile_no') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <div class="checkbox"> <label> <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me </label> </div> </div> </div> <div class="form-group"> <div class="col-md-8 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Login </button> <a class="btn btn-link" href="{{ route('password.request') }}"> Forgot Your Password? </a> </div> </div> </form> </div> </div> </div> </div> </div> @endsection Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/login If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...
How To Set Multi Authentication in JWT
Today, laravelcode share with you how to set multi authentication in jwt with simple example. recently we are working with one laravel application and we are also built API for it. and we are required more then one table for authentication. you also see in JWT documentation it by default provide User model for authentication. but sometime we have required use another table also use for authentication in our API. for Ex. one for front API user and another for Admin API user. This problem you easyly handle by help of this tutorials. please simple follow this step. You may also check this link for JWT configure in laravel Restful API In Laravel 5.5 Using jwt Authentication Suppose we have two table which we are want for authentication with JWT 1. users 2. admins Step : 1 Add following route in routes/api.php Route::post('auth/userlogin', 'ApiController@userLogin'); Route::post('auth/adminlogin', 'ApiController@adminLogin'); Step : 2 Create Controller namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests; use Config; use JWTAuth; use JWTAuthException; use App\User; use App\Admin; class ApiController extends Controller { public function __construct() { $this->user = new User; $this->admin = new Admin; } public function userLogin(Request $request){ Config::set('jwt.user', 'App\User'); Config::set('auth.providers.users.model', \App\User::class); $credentials = $request->only('email', 'password'); $token = null; try { if (!$token = JWTAuth::attempt($credentials)) { return response()->json([ 'response' => 'error', 'message' => 'invalid_email_or_password', ]); } } catch (JWTAuthException $e) { return response()->json([ 'response' => 'error', 'message' => 'failed_to_create_token', ]); } return response()->json([ 'response' => 'success', 'result' => [ 'token' => $token, 'message' => 'I am front user', ], ]); } public function adminLogin(Request $request){ Config::set('jwt.user', 'App\Admin'); Config::set('auth.providers.users.model', \App\Admin::class); $credentials = $request->only('email', 'password'); $token = null; try { if (!$token = JWTAuth::attempt($credentials)) { return response()->json([ 'response' => 'error', 'message' => 'invalid_email_or_password', ]); } } catch (JWTAuthException $e) { return response()->json([ 'response' => 'error', 'message' => 'failed_to_create_token', ]); } return response()->json([ 'response' => 'success', 'result' => [ 'token' => $token, 'message' => 'I am Admin user', ], ]); } } [ADDCODE] Step : 9 Test With Postman You can test your API with postman and another API testing tool Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000 If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...
Restful API In Laravel 5.5 Using jwt Authentication
Today, we are share with you how to built restful API in laravel using JWT(JSON Web Token). it is very eassy and simple implementation in laravel. when you work with larg application and you also want make mobile or android application for this project. you should be write API layer or API for your application which help communication with your android app and your live server. In simple term in API is you pass some argument as a url GET request and POST request from app and server first check this API url is valid or not and then send some output data in json formate and android or mobile application develoer manage it. In laravel you want to buitl API then JWT(JSON Web Token) is best for it and easy to use. and it also good for apply security on your RESTful API Simple follow this step and integrate JWT(JSON Web Token) in your laravel application. You are also manage multi authentiication with JWT(JSON Web Token) check this link JWT(JSON Web Token) multi authentication Step : 1 Install tymon/jwt-auth package in your laravel application First we need to install tymon/jwt-auth in our laravel application using following command composer require tymon/jwt-auth after intallation tymon/jwt-auth package in your laravel application, then config it like tha.. Step : 2 Make some changes in config/app.php file Now open your config/app.php file and set service provider and their aliase. 'providers' => [ .... Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class, ], 'aliases' => [ .... 'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class, ], [ADDCODE] Step : 3 Generate configuration file After this completion then after publish configuration file using following command. php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider" After run this command then config/jwt.php file generated automatic. and it look like this. if you want some custom configer in it you should make in this file. /* * This file is part of jwt-auth. * * (c) Sean Tymon * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return [ /* |-------------------------------------------------------------------------- | JWT Authentication Secret |-------------------------------------------------------------------------- | | Don't forget to set this, as it will be used to sign your tokens. | A helper command is provided for this: `php artisan jwt:generate` | */ 'secret' => env('JWT_SECRET', 'obOoFDiAihNZE6kPtX6WQXOErPvuY3Oe'), /* |-------------------------------------------------------------------------- | JWT time to live |-------------------------------------------------------------------------- | | Specify the length of time (in minutes) that the token will be valid for. | Defaults to 1 hour | */ 'ttl' => 600, /* |-------------------------------------------------------------------------- | Refresh time to live |-------------------------------------------------------------------------- | | Specify the length of time (in minutes) that the token can be refreshed | within. I.E. The user can refresh their token within a 2 week window of | the original token being created until they must re-authenticate. | Defaults to 2 weeks | */ 'refresh_ttl' => 20160, /* |-------------------------------------------------------------------------- | JWT hashing algorithm |-------------------------------------------------------------------------- | | Specify the hashing algorithm that will be used to sign the token. | | See here: https://github.com/namshi/jose/tree/2.2.0/src/Namshi/JOSE/Signer | for possible values | */ 'algo' => 'HS256', /* |-------------------------------------------------------------------------- | User Model namespace |-------------------------------------------------------------------------- | | Specify the full namespace to your User model. | e.g. 'Acme\Entities\User' | */ 'user' => 'App\User', /* |-------------------------------------------------------------------------- | User identifier |-------------------------------------------------------------------------- | | Specify a unique property of the user that will be added as the 'sub' | claim of the token payload. | */ 'identifier' => 'id', /* |-------------------------------------------------------------------------- | Required Claims |-------------------------------------------------------------------------- | | Specify the required claims that must exist in any token. | A TokenInvalidException will be thrown if any of these claims are not | present in the payload. | */ 'required_claims' => ['iss', 'iat', 'exp', 'nbf', 'sub', 'jti'], /* |-------------------------------------------------------------------------- | Blacklist Enabled |-------------------------------------------------------------------------- | | In order to invalidate tokens, you must have the blacklist enabled. | If you do not want or need this functionality, then set this to false. | */ 'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true), /* |-------------------------------------------------------------------------- | Providers |-------------------------------------------------------------------------- | | Specify the various providers used throughout the package. | */ 'providers' => [ /* |-------------------------------------------------------------------------- | User Provider |-------------------------------------------------------------------------- | | Specify the provider that is used to find the user based | on the subject claim | */ 'user' => 'Tymon\JWTAuth\Providers\User\EloquentUserAdapter', /* |-------------------------------------------------------------------------- | JWT Provider |-------------------------------------------------------------------------- | | Specify the provider that is used to create and decode the tokens. | */ 'jwt' => 'Tymon\JWTAuth\Providers\JWT\NamshiAdapter', /* |-------------------------------------------------------------------------- | Authentication Provider |-------------------------------------------------------------------------- | | Specify the provider that is used to authenticate users. | */ 'auth' => 'Tymon\JWTAuth\Providers\Auth\IlluminateAuthAdapter', /* |-------------------------------------------------------------------------- | Storage Provider |-------------------------------------------------------------------------- | | Specify the provider that is used to store tokens in the blacklist | */ 'storage' => 'Tymon\JWTAuth\Providers\Storage\IlluminateCacheAdapter', ], ]; Bydefault User model use for authentication but if you want use another model for authentication you can change it. You are also manage multi authentiication with JWT(JSON Web Token) check this link JWT(JSON Web Token) multi authentication Step : 4 Generate JWT Token Now for token encryption, I need to generate a secret key by running following line of code usign following command For laravel 5.4 or downgrade version php artisan jwt:generate For laravel 5.5 php artisan jwt:secret Following Error Only Generate In Laravel 5.5 If you run above command and you face following Error message in terminal. generally this error accur in laravel5.5 version. we have also solution for it. [ReflectionException] Method Tymon\JWTAuth\Commands\JWTGenerateCommand::handle() does not exist Solution Please, install new dev version of tymon/jwt-auth package. this issue resolve in dev package development. so, again run following command for install dev version package. composer require tymon/jwt-auth:dev-develop --prefer-source After install dev version package open your config/app.php file and replace old service provider to new like that. 'providers' => [ .... Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class to Tymon\JWTAuth\Providers\LaravelServiceProvider::class ], After replace service provider then now run following command for generate jwt key php artisan jwt:secret Step : 5 Create middleware for JWT Now we are create middleware for JWT. open your app/Http/Middleware folder and create one authJWT.php file and put into it followign code. namespace App\Http\Middleware; use Closure; use JWTAuth; use Exception; class authJWT { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { try { $user = JWTAuth::toUser($request->input('token')); } catch (Exception $e) { if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){ return response()->json(['error'=>'Token is Invalid']); }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){ return response()->json(['error'=>'Token is Expired']); }else{ return response()->json(['error'=>'Something is wrong']); } } return $next($request); } } Step : 6 Register Middleware We are create middleware for JWT now we are need to Register it. open your app/Http/Kernel.php file and make following changes namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { ... ... protected $routeMiddleware = [ ... 'jwt-auth' => \App\Http\Middleware\authJWT::class, ]; } Step : 7 Add following route in routes/api.php Laravel provide routes/api.php file for write API route and this is best for manage all API route in it. so our web application route and API route not mix. Look at in bellow route you can see i use two middleware "api" and "cors". cors is not mandatory, but Sometime you make API and call it then you get the following error message so we are create those two middleware for avoide this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://test.com/api/register. (Reason: CORS header 'Access-Control-Allow-Origin' missing)." You also found how to create this middleware open this link Ajax - Cross-Origin Request Blocked in Larave 5?.   Route::group(['middleware' => ['api','cors']], function () { Route::post('auth/login', 'ApiController@login'); Route::group(['middleware' => 'jwt.auth'], function () { Route::get('user', 'ApiController@getAuthUser'); }); }); Step : 8 Create Controller Now we are create controller, so create ApiController.php file in your app/Http/Controllers folder. namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests; use JWTAuth; use JWTAuthException; use App\User; class ApiController extends Controller { public function __construct() { $this->user = new User; } public function login(Request $request){ $credentials = $request->only('email', 'password'); $token = null; try { if (!$token = JWTAuth::attempt($credentials)) { return response()->json([ 'response' => 'error', 'message' => 'invalid_email_or_password', ]); } } catch (JWTAuthException $e) { return response()->json([ 'response' => 'error', 'message' => 'failed_to_create_token', ]); } return response()->json([ 'response' => 'success', 'result' => [ 'token' => $token, ], ]); } public function getAuthUser(Request $request){ $user = JWTAuth::toUser($request->token); return response()->json(['result' => $user]); } } Step : 9 Test With Postman You can test your API with postman and another API testing tool Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000 If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...
Image Optimization In Laravel With Spatie
Today, Laravelcode share with you one of the helpfull tutorials aboute how to image optimization in laravel using spatie laravel package. because image optimization is very needed when we are working on big project and lots of images use in it. it image optimization functionality also help us in project size reduce. Here we are show how to image optimization in laravel using spatie laravel package. how to use in laravel application step by step. Step : 1 Install package First we need to install spatie laravel package in our laravel application run following command. composer require spatie/laravel-image-optimizer Step : 2 Configure package After installtion done then configure package. so, open our config/app.php file and set service provider and aliases in it. just following this way 'providers' => [ .... Spatie\LaravelImageOptimizer\ImageOptimizerServiceProvider::class, ], 'aliases' => [ .... 'ImageOptimizer' => Spatie\LaravelImageOptimizer\ImageOptimizerFacade::class, ], Then after public confige run following command php artisan vendor:publish --provider="Spatie\LaravelImageOptimizer\ImageOptimizerServiceProvider" After run this command and open your config/image-optimizer.php file it look like this. if your want to change any configure value then change according your requirement. use Spatie\ImageOptimizer\Optimizers\Svgo; use Spatie\ImageOptimizer\Optimizers\Optipng; use Spatie\ImageOptimizer\Optimizers\Gifsicle; use Spatie\ImageOptimizer\Optimizers\Pngquant; use Spatie\ImageOptimizer\Optimizers\Jpegoptim; return [ /* * When calling `optimize` the package will automatically determine which optimizers * should run for the given image. */ 'optimizers' => [ Jpegoptim::class => [ '--strip-all', // this strips out all text information such as comments and EXIF data '--all-progressive', // this will make sure the resulting image is a progressive one ], Pngquant::class => [ '--force', // required parameter for this package ], Optipng::class => [ '-i0', // this will result in a non-interlaced, progressive scanned image '-o2', // this set the optimization level to two (multiple IDAT compression trials) '-quiet', // required parameter for this package ], Svgo::class => [ '--disable=cleanupIDs', // disabling because it is know to cause troubles ], Gifsicle::class => [ '-b', // required parameter for this package '-O3', // this produces the slowest but best results ], ], /* * The maximum time in seconds each optimizer is allowed to run separately. */ 'timeout' => 60, /* * If set to `true` all output of the optimizer binaries will be appended to the default log. * You can also set this to a class that implements `Psr\Log\LoggerInterface`. */ 'log_optimizer_activity' => false, ]; Step : 3 Add Middleware This package provide it's own middleware for image optimization just open your app/Http/Kernel.php file and add middleware like that. [ADDCODE] protected $routeMiddleware = [ ... 'optimizeImages' => \Spatie\LaravelImageOptimizer\Middlewares\OptimizeImages::class, ]; Step : 4 Create Route Now create route for image post request Route::post('/photos', 'PhotosController@store') ->middleware('optimizeImages'); Step : 5 Create Controller Now, create controller create PhotosController.php file in app/Http/Controllers folder and put into it following code. namespace App\Http\Controllers; class PhotosController extends Controller { public function store() { $this->validate(request(), [ 'photo' => 'required|image:jpeg ' ]); request()->photo->storeAs('images', 'optimized.jpg'); /Session::put('success', 'Your Image Successfully Optimize') return redirect()->back(); } } Step : 6 Create Blade File Now, create one view file for display image upload form and put itno it following code. @if($message = Session::get('success')) <div class="alert alert-info alert-dismissible fade in" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Success!</strong> {{ $message }} </div> @endif <form action="/photos" enctype="multipart/form-data" method="POST"> {{ csrf_field() }} <div class="form-group"> <label for="">Photo</label> <input class="form-control" name="photo" type="file" /> <button type="submit">Upload</button> </div> </form> Note : if your want more information then click on this link for this package Spatie Package If you face any problem then please write a comment or give some suggestions for improvement. Thanks...
Laravel 5.4 Users Authorization With Spatie Laravel-Permission
Today, Laravelcode share with you a very helfull tutorials related laravel role base permission system, we are share with you Laravel 5.4 Usesr Authorization With Spatie Laravel-Permission. When you are craete any big lavel laravel application you must be needed set up user access control list (ACL) functionality for manage user role and permission for some perticuler right and athority. you manage all enty user managemant system base on role and permission which user can access which type functionality in your application. for example you ecreate one blog system and you want to give some perticuler permission to some perticuler user like some user only create blog post, some user only show blog post and they will be not to able to create blog post and not also delete any blog post. this is basic stuff for user access controll list(ACL) functionality. Here, we are share with you how to create user access control list(ACL) functionality with laravel application using Spatie Laravel-Permission laravel package We are apply access control list(ACL) on post article in this tutorials. We are share here all code step by step so, please follow this step for crating laravel access control list(ACL) role permission step by step. First we are starting look somethis it's method and how is work givePermissionTo(): Allows us to give persmission to a user or role revokePermissionTo(): Revoke permission from a user or role hasPermissionTo(): Check if a user or role has a given permission assignRole(): Assigns role to a user removeRole(): Removes role from a user hasRole(): Checks if a user has a role hasAnyRole(Role::all()): Checks if a user has any of a given list of roles hasAllRoles(Role::all()): Checks if a user has all of a given list of role Step : 1 Install Required Packages We are first need to install Spatie Laravel-Permission package. please run following comand for install this package in your laravel application. composer require spatie/laravel-permission Step : 2 Configure Packages Now open your confige/app.php file and add package service provider into providers array like that 'providers' => [ ... Spatie\Permission\PermissionServiceProvider::class, ]; Now, we need to public or create this package's bydefault migration file by run following command : php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations" Then after done this this proccess run migration by followign command : php artisan migrate Now, open your database and look into that their followign table created : permissions : In this table we are store varius of permission roles : In this table we are store user role role_has_permission : This is one type of pivot table for relationship between permissions and roles table model_has_roles : This also pivot table for relationship between roles and users table model_has_permissions : This also pivot table for relationship between users and permissions table Okay, now we are public configuration file by run following command : php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config" Step : 3 Make changes in views/layout/app.blade.php file Now, open your views/layout/app.blade.php file and here you make some changes like that simple put following all code in your file. <!DOCTYPE html> <html lang="{{ config('app.locale') }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta id="token" name="csrf-token" value="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> <script> window.csrf = "{{ csrf_token() }}"; </script> </head> <body> <div id=""> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.name', 'Laravel') }} </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav"> <li><a href="{{ url('/') }}">Home</a></li> @if (!Auth::guest()) <li><a href="{{ route('posts.create') }}">New Article</a></li> @endif </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @if (Auth::guest()) <li><a href="{{ route('login') }}">Login</a></li> <li><a href="{{ route('register') }}">Register</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> {{ Auth::user()->name }} <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li> <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </li> </ul> </li> @endif </ul> </div> </div> </nav> @if(Session::has('flash_message')) <div class="container"> <div class="alert alert-success"><em> {!! session('flash_message') !!}</em> </div> </div> @endif <div class="row"> <div class="col-md-8 col-md-offset-2"> @include ('errors.list') {{-- Including error file --}} </div> </div> @yield('content') </div> <!-- Scripts --> <script src="{{ asset('js/app.js') }}"></script> </body> </html> Step : 4 Create Routes [ADDCODE] After changes in app.blade.php file then create following route in your web.php file. // Laravel welcome route. Route::get('/', function () { return view('welcome'); }); // Laravel auth route. Auth::routes(); Route::get('/', 'PostController@index')->name('home'); // Users resource route. Route::resource('users', 'UserController'); // Roles resource route. Route::resource('roles', 'RoleController'); // Permissions resource route. Route::resource('permissions', 'PermissionController'); // Post resource route. Route::resource('posts', 'PostController'); Step : 5 Create Post Migration Now, we are craete post migration using this command : php artisan make:migration crate_post_tbl Then open created post migration file from this path database/migrations and put inti it followign code. use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostTbl extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('post', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } public function down() { Schema::drop("post"); } } Step : 6 Create Post Model Now, create one post model in this path app/Post.php file and put following code into it. namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { public $table = 'post'; public $fillable = ['title','description']; } Step : 7 Create Post Controller After post model created then we need to create controller in this path app/Http/Controllers/PostController.php file and put following code. namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use Auth; use Session; class PostController extends Controller { public function __construct() { $this->middleware(['auth', 'clearance'])->except('index', 'show'); } public function index() { $posts = Post::orderby('id', 'desc')->paginate(5); return view('posts.index', compact('posts')); } public function create() { return view('posts.create'); } public function store(Request $request) { //Validation $this->validate($request, [ 'title'=>'required|max:100', 'description' =>'required', ]); $title = $request['title']; $body = $request['description']; $post = Post::create($request->only('title', 'description')); //Display a successful message upon save return redirect()->route('posts.index') ->with('flash_message', 'Post, '. $post->title.' created'); } public function show($id) { $post = Post::findOrFail($id); return view ('posts.show', compact('post')); } public function edit($id) { $post = Post::findOrFail($id); return view('posts.edit', compact('post')); } public function update(Request $request, $id) { $this->validate($request, [ 'title'=>'required|max:100', 'description'=>'required', ]); $post = Post::findOrFail($id); $post->title = $request->input('title'); $post->body = $request->input('description'); $post->save(); return redirect()->route('posts.show', $post->id)->with('flash_message', 'Post, '. $post->title.' updated'); } public function destroy($id) { $post = Post::findOrFail($id); $post->delete(); return redirect()->route('posts.index') ->with('flash_message', 'Post successfully deleted'); } } Step : 8 Create View Files We are user four view file in our PostController.php file. so, we must be create all view/blade files. we are created following blade file for Post Module. 1) \resources\views\posts\index.blade.php 2) \resources\views\posts\create.blade.php 3) \resources\views\posts\show.blade.php 4) \resources\views\posts\edit.blade.php Our index.blade.php look like. @extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default"> <div class="panel-heading"><h3>Posts</h3></div> <div class="panel-heading"> Page {{ $posts->currentPage() }} of {{ $posts->lastPage() }} </div> @foreach ($posts as $post) <div class="panel-body"> <li style="list-style-type:disc"> <a href="{{ route('posts.show', $post->id ) }}"><b>{{ $post->title }}</b><br> <p class="teaser"> {{ str_limit($post->description, 100) }} </p> </a> </li> </div> @endforeach </div> <div class="text-center"> {!! $posts->links() !!} </div> </div> </div> </div> @endsection Our create.blade.php look like. @extends('layouts.app') @section('title', '| Create New Post') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Create New Post</h1> <hr> {{ Form::open(array('route' => 'posts.store')) }} <div class="form-group"> {{ Form::label('title', 'Title') }} {{ Form::text('title', null, array('class' => 'form-control')) }} <br> {{ Form::label('body', 'Post Body') }} {{ Form::textarea('body', null, array('class' => 'form-control')) }} <br> {{ Form::submit('Create Post', array('class' => 'btn btn-success btn-lg btn-block')) }} {{ Form::close() }} </div> </div> </div> @endsection Our create.blade.php look like. @extends('layouts.app') @section('title', '| Create New Post') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Create New Post</h1> <hr> {{ Form::open(array('route' => 'posts.store')) }} <div class="form-group"> {{ Form::label('title', 'Title') }} {{ Form::text('title', null, array('class' => 'form-control')) }} <br> {{ Form::label('description', 'Post Description') }} {{ Form::textarea('description', null, array('class' => 'form-control')) }} <br> {{ Form::submit('Create Post', array('class' => 'btn btn-success btn-lg btn-block')) }} {{ Form::close() }} </div> </div> </div> @endsection Our show.blade.php look like. @extends('layouts.app') @section('title', '| View Post') @section('content') <div class="container"> <h1>{{ $post->title }}</h1> <hr> <p class="lead">{{ $post->description }} </p> <hr> {!! Form::open(['method' => 'DELETE', 'route' => ['posts.destroy', $post->id] ]) !!} <a href="{{ url()->previous() }}" class="btn btn-primary">Back</a> @can('Edit Post') <a href="{{ route('posts.edit', $post->id) }}" class="btn btn-info" role="button">Edit</a> @endcan @can('Delete Post') {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} @endcan {!! Form::close() !!} </div> @endsection Our edit.blade.php look like. @extends('layouts.app') @section('title', '| Edit Post') @section('content') <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Edit Post</h1> <hr> {{ Form::model($post, array('route' => array('posts.update', $post->id), 'method' => 'PUT')) }} <div class="form-group"> {{ Form::label('title', 'Title') }} {{ Form::text('title', null, array('class' => 'form-control')) }} <br> {{ Form::label('description', 'Post Description') }} {{ Form::textarea('description', null, array('class' => 'form-control')) }} <br> {{ Form::submit('Save', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> </div> </div> @endsection Now, run your laraval application and once you check your post module work perfect? (Here we have not still create middleware so only working home page but you are login and try to create new post then it's show error it's not big problem just continue...) it's all working okay then move anothe left step Step : 9 Create User Controller Now, we are create user module's controller and all view files. we have already User.php model for user so, this is not needed for create once again. we need to some changes like that. Just open app/User.php file and put following code into it. namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use Notifiable; use HasRoles; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function setPasswordAttribute($password) { $this->attributes['password'] = bcrypt($password); } } create app/Http/Controllers/UserController.php file and put into it following code. namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use Auth; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class UserController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']); //middleware } public function index() { $users = User::all(); return view('users.index')->with('users', $users); } public function create() { $roles = Role::get(); return view('users.create', ['roles'=>$roles]); } public function store(Request $request) { $this->validate($request, [ 'name'=>'required|max:120', 'email'=>'required|email|unique:users', 'password'=>'required|min:6|confirmed' ]); $user = User::create($request->only('email', 'name', 'password')); $roles = $request['roles']; //Retrieving the roles field //Checking if a role was selected if (isset($roles)) { foreach ($roles as $role) { $role_r = Role::where('id', '=', $role)->firstOrFail(); $user->assignRole($role_r); //Assigning role to user } } //Redirect to the users.index view and display message return redirect()->route('users.index') ->with('flash_message', 'User successfully added.'); } public function show($id) { return redirect('users'); } public function edit($id) { $user = User::findOrFail($id); $roles = Role::get(); //Get all roles return view('users.edit', compact('user', 'roles')); //pass user and roles data to view } public function update(Request $request, $id) { $user = User::findOrFail($id); $this->validate($request, [ 'name'=>'required|max:120', 'email'=>'required|email|unique:users,email,'.$id, 'password'=>'required|min:6|confirmed' ]); $input = $request->only(['name', 'email', 'password']); $roles = $request['roles']; $user->fill($input)->save(); if (isset($roles)) { $user->roles()->sync($roles); } else { $user->roles()->detach(); } return redirect()->route('users.index') ->with('flash_message', 'User successfully edited.'); } public function destroy($id) { $user = User::findOrFail($id); $user->delete(); return redirect()->route('users.index') ->with('flash_message', 'User successfully deleted.'); } } After done created UserController.php file then create all following blade file. 1) \resources\views\users\index.blade.php 2) \resources\views\users\create.blade.php 3) \resources\views\users\edit.blade.php Our inde.blade.php look like. @extends('layouts.app') @section('title', '| Users') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-users"></i> User Administration <a href="{{ route('roles.index') }}" class="btn btn-default pull-right">Roles</a> <a href="{{ route('permissions.index') }}" class="btn btn-default pull-right">Permissions</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Date/Time Added</th> <th>User Roles</th> <th>Actions</th> </tr> </thead> <tbody> @foreach ($users as $user) <tr> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->created_at->format('F d, Y h:ia') }}</td> <td>{{ $user->roles()->pluck('name')->implode(' ') }}</td>{{-- Retrieve array of roles associated to a user and convert to string --}} <td> <a href="{{ route('users.edit', $user->id) }}" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="{{ route('users.create') }}" class="btn btn-success">Add User</a> </div> @endsection Our create.blade.php look like. @extends('layouts.app') @section('title', '| Add User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Add User</h1> <hr> {{ Form::open(array('url' => 'users')) }} <div class="form-group"> {{ Form::label('name', 'Name') }} {{ Form::text('name', '', array('class' => 'form-control')) }} </div> <div class="form-group"> {{ Form::label('email', 'Email') }} {{ Form::email('email', '', array('class' => 'form-control')) }} </div> <div class='form-group'> @foreach ($roles as $role) {{ Form::checkbox('roles[]', $role->id ) }} {{ Form::label($role->name, ucfirst($role->name)) }} <br> @endforeach </div> <div class="form-group"> {{ Form::label('password', 'Password') }} <br> {{ Form::password('password', array('class' => 'form-control')) }} </div> <div class="form-group"> {{ Form::label('password', 'Confirm Password') }} <br> {{ Form::password('password_confirmation', array('class' => 'form-control')) }} </div> {{ Form::submit('Add', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection Our edit.blade.php look like. @extends('layouts.app') @section('title', '| Edit User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Edit {{$user->name}}</h1> <hr> {{ Form::model($user, array('route' => array('users.update', $user->id), 'method' => 'PUT')) }} <div class="form-group"> {{ Form::label('name', 'Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <div class="form-group"> {{ Form::label('email', 'Email') }} {{ Form::email('email', null, array('class' => 'form-control')) }} </div> <h5><b>Give Role</b></h5> <div class='form-group'> @foreach ($roles as $role) {{ Form::checkbox('roles[]', $role->id, $user->roles ) }} {{ Form::label($role->name, ucfirst($role->name)) }} <br> @endforeach </div> <div class="form-group"> {{ Form::label('password', 'Password') }} <br> {{ Form::password('password', array('class' => 'form-control')) }} </div> <div class="form-group"> {{ Form::label('password', 'Confirm Password') }} <br> {{ Form::password('password_confirmation', array('class' => 'form-control')) }} </div> {{ Form::submit('Add', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection Now, we are done our users module. then go nex step... Step : 10 Create PermissionController Controller Now, we are create our Permissions module. here we are create PermissionController and all views/blades file. So, first create controller go this path and create app/Http/Controllers/PermissionController.php file and put following code into it. namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class PermissionController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']); //middleware } public function index() { $permissions = Permission::all(); return view('permissions.index')->with('permissions', $permissions); } public function create() { $roles = Role::get(); return view('permissions.create')->with('roles', $roles); } public function store(Request $request) { $this->validate($request, [ 'name'=>'required|max:40', ]); $name = $request['name']; $permission = new Permission(); $permission->name = $name; $roles = $request['roles']; $permission->save(); if (!empty($request['roles'])) { //If one or more role foreach ($roles as $role) { $r = Role::where('id', '=', $role)->firstOrFail(); $permission = Permission::where('name', '=', $name)->first(); $r->givePermissionTo($permission); } } return redirect()->route('permissions.index') ->with('flash_message', 'Permission'. $permission->name.' added!'); } public function show($id) { return redirect('permissions'); } public function edit($id) { $permission = Permission::findOrFail($id); return view('permissions.edit', compact('permission')); } public function update(Request $request, $id) { $permission = Permission::findOrFail($id); $this->validate($request, [ 'name'=>'required|max:40', ]); $input = $request->all(); $permission->fill($input)->save(); return redirect()->route('permissions.index') ->with('flash_message', 'Permission'. $permission->name.' updated!'); } public function destroy($id) { $permission = Permission::findOrFail($id); if ($permission->name == "Administer roles & permissions") { return redirect()->route('permissions.index') ->with('flash_message', 'Cannot delete this Permission!'); } $permission->delete(); return redirect()->route('permissions.index') ->with('flash_message', 'Permission deleted!'); } } After done created controller then we are followign three view needed : 1) \resources\views\permissions\index.blade.php 2) \resources\views\permissions\create.blade.php 3) \resources\views\permissions\edit.blade.php Our index.blade.php look like. @extends('layouts.app') @section('title', '| Permissions') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-key"></i>Available Permissions <a href="{{ route('users.index') }}" class="btn btn-default pull-right">Users</a> <a href="{{ route('roles.index') }}" class="btn btn-default pull-right">Roles</a></h1> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Permissions</th> <th>Operation</th> </tr> </thead> <tbody> @foreach ($permissions as $permission) <tr> <td>{{ $permission->name }}</td> <td> <a href="{{ URL::to('permissions/'.$permission->id.'/edit') }}" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['permissions.destroy', $permission->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="{{ URL::to('permissions/create') }}" class="btn btn-success">Add Permission</a> </div> @endsection Our create.blade.php look like. @extends('layouts.app') @section('title', '| Create Permission') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Add Permission</h1> <br> {{ Form::open(array('url' => 'permissions')) }} <div class="form-group"> {{ Form::label('name', 'Name') }} {{ Form::text('name', '', array('class' => 'form-control')) }} </div><br> @if(!$roles->isEmpty()) //If no roles exist yet <h4>Assign Permission to Roles</h4> @foreach ($roles as $role) {{ Form::checkbox('roles[]', $role->id ) }} {{ Form::label($role->name, ucfirst($role->name)) }} <br> @endforeach @endif <br> {{ Form::submit('Add', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection Our edit.blade.php look like. @extends('layouts.app') @section('title', '| Edit Permission') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Edit {{$permission->name}}</h1> <br> {{ Form::model($permission, array('route' => array('permissions.update', $permission->id), 'method' => 'PUT')) }} <div class="form-group"> {{ Form::label('name', 'Permission Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <br> {{ Form::submit('Edit', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection After done Permissions module we are move our last module Roles Step : 11 Create RoleController Controller Now, we are create RoleController.php file and also their views file like that way. Now create RoleController.php file in app/Http/Controllers folder and put into it following code. namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use Session; class RoleController extends Controller { public function __construct() { $this->middleware(['auth', 'isAdmin']);//middleware } public function index() { $roles = Role::all(); return view('roles.index')->with('roles', $roles); } public function create() { $permissions = Permission::all(); return view('roles.create', ['permissions'=>$permissions]); } public function store(Request $request) { $this->validate($request, [ 'name'=>'required|unique:roles|max:10', 'permissions' =>'required', ] ); $name = $request['name']; $role = new Role(); $role->name = $name; $permissions = $request['permissions']; $role->save(); foreach ($permissions as $permission) { $p = Permission::where('id', '=', $permission)->firstOrFail(); $role = Role::where('name', '=', $name)->first(); $role->givePermissionTo($p); } return redirect()->route('roles.index') ->with('flash_message', 'Role'. $role->name.' added!'); } public function show($id) { return redirect('roles'); } public function edit($id) { $role = Role::findOrFail($id); $permissions = Permission::all(); return view('roles.edit', compact('role', 'permissions')); } public function update(Request $request, $id) { $role = Role::findOrFail($id); $this->validate($request, [ 'name'=>'required|max:10|unique:roles,name,'.$id, 'permissions' =>'required', ]); $input = $request->except(['permissions']); $permissions = $request['permissions']; $role->fill($input)->save(); $p_all = Permission::all(); foreach ($p_all as $p) { $role->revokePermissionTo($p); } foreach ($permissions as $permission) { $p = Permission::where('id', '=', $permission)->firstOrFail(); $role->givePermissionTo($p); } return redirect()->route('roles.index') ->with('flash_message', 'Role'. $role->name.' updated!'); } public function destroy($id) { $role = Role::findOrFail($id); $role->delete(); return redirect()->route('roles.index') ->with('flash_message', 'Role deleted!'); } } After create RoleController then create following three views/blades file. 1) \resources\views\roles\index.blade.php 2) \resources\views\roles\create.blade.php 3) \resources\views\roles\edit.blade.php Our index.blade.php look like. @extends('layouts.app') @section('title', '| Roles') @section('content') <div class="col-lg-10 col-lg-offset-1"> <h1><i class="fa fa-key"></i> Roles <a href="{{ route('users.index') }}" class="btn btn-default pull-right">Users</a> <a href="{{ route('permissions.index') }}" class="btn btn-default pull-right">Permissions</a></h1> <hr> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Role</th> <th>Permissions</th> <th>Operation</th> </tr> </thead> <tbody> @foreach ($roles as $role) <tr> <td>{{ $role->name }}</td> <td>{{ str_replace(array('[',']','"'),'', $role->permissions()->pluck('name')) }}</td> <td> <a href="{{ URL::to('roles/'.$role->id.'/edit') }}" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['roles.destroy', $role->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> <a href="{{ URL::to('roles/create') }}" class="btn btn-success">Add Role</a> </div> @endsection Our create.blade.php look like. @extends('layouts.app') @section('title', '| Add Role') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Add Role</h1> <hr> {{ Form::open(array('url' => 'roles')) }} <div class="form-group"> {{ Form::label('name', 'Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <h5><b>Assign Permissions</b></h5> <div class='form-group'> @foreach ($permissions as $permission) {{ Form::checkbox('permissions[]', $permission->id ) }} {{ Form::label($permission->name, ucfirst($permission->name)) }} <br> @endforeach </div> {{ Form::submit('Add', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection Our edit.blade.php look like. @extends('layouts.app') @section('title', '| Edit Role') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Edit Role: {{$role->name}}</h1> <hr> {{ Form::model($role, array('route' => array('roles.update', $role->id), 'method' => 'PUT')) }} <div class="form-group"> {{ Form::label('name', 'Role Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <h5><b>Assign Permissions</b></h5> @foreach ($permissions as $permission) {{Form::checkbox('permissions[]', $permission->id, $role->permissions ) }} {{Form::label($permission->name, ucfirst($permission->name)) }} <br> @endforeach <br> {{ Form::submit('Edit', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection Okay we are done all module now just remaining two middleware one is isAdmin and secont one is ClearanceMiddleware Step : 12 Create isAdmin Middleware Why we are create isAdmin middleware? this middleware is check user's To restrict access to the roles and permissions page, Create AdminMiddleware.php file in this path app/Http/Middleware/ and put into followign code. namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; use App\User; class AdminMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = User::all()->count(); if (!($user == 1)) { if (!Auth::user()->hasPermissionTo('Administer roles & permissions')) { abort('401'); } } return $next($request); } } After create AdminMiddleware.php then create second middleware. Step : 13 Create clearance Middleware Create ClearanceMiddleware.php file in this path app/Http/Middleware/ and put into followign code. namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class ClearanceMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (Auth::user()->hasPermissionTo('Administer roles & permissions')) { return $next($request); } if ($request->is('posts/create')) { if (!Auth::user()->hasPermissionTo('Create Post')) { abort('401'); } else { return $next($request); } } if ($request->is('posts/*/edit')) { if (!Auth::user()->hasPermissionTo('Edit Post')) { abort('401'); } else { return $next($request); } } if ($request->isMethod('Delete')) { if (!Auth::user()->hasPermissionTo('Delete Post')) { abort('401'); } else { return $next($request); } } return $next($request); } } Step : 14 Add Middleware in kernel.php File After done both of middleware then we must be needed add both of middleware into kernel.php file like that Open /app/Http/kernel.php file and add following two line in bottom protected $routeMiddleware = [ ...... ...... 'isAdmin' => \App\Http\Middleware\AdminMiddleware::class, 'clearance' => \App\Http\Middleware\ClearanceMiddleware::class, ]; Step : 15 Create 401 page In both of middleware when condition is false then they redirect to 401. so, we are create one static page for handle this 401 error Create one 401.blade.php file in this path \resources\views\errors and put into follwowing simple html code. @extends('layouts.app') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><center>401<br> ACCESS DENIED</center></h1> </div> @endsection Now, we are done all things so please add some dummy role and permisssion the open following url in your browser. http://localhost:8000/permissions Step : 15 Create Seeder for dummy data. If you don't know how to added manualy records for permissions and role table then create one seed file, just open database/seeds/DatabaseSeeder.php file and put like that code for insert some dummy permissions records and also create admin user. use Illuminate\Database\Seeder; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Ask for db migration refresh, default is no if ($this->command->confirm('Do you wish to refresh migration before seeding, it will clear all old data ?')) { // Call the php artisan migrate:refresh $this->command->call('migrate:refresh'); $this->command->warn("Data cleared, starting from blank database."); } // Seed the default permissions Permission::firstOrCreate(['name' => 'Administer roles & permissions', 'guard_name' => 'isAdmin']); $this->command->info('Default Permissions added.'); // Confirm roles needed if ($this->command->confirm('Create Roles for user, default is admin and user? [y|N]', true)) { // Ask for roles from input $input_roles = $this->command->ask('Enter roles in comma separate format.', 'Admin,User'); // Explode roles $roles_array = explode(',', $input_roles); // add roles foreach($roles_array as $role) { $role = Role::firstOrCreate(['name' => trim($role), 'guard_name' => 'isAdmin']); if( $role->name == 'Admin' ) { // assign all permissions $role->syncPermissions(Permission::all()); $this->command->info('Admin granted all the permissions'); } else { // for others by default only read access $role->syncPermissions(Permission::where('name', 'LIKE', 'view_%')->get()); } // create one user for each role $this->createUser($role); } $this->command->info('Roles ' . $input_roles . ' added successfully'); } else { Role::firstOrCreate(['name' => 'User']); $this->command->info('Added only default user role.'); } // now lets seed some posts for demo $this->command->info('Some Posts data seeded.'); $this->command->warn('All done :)'); } /** * Create a user with given role * * @param $role */ private function createUser($role) { $user = factory(User::class)->create(); $user->assignRole($role->name); if( $role->name == 'Admin' ) { $this->command->info('Here is your admin details to login:'); $this->command->warn($user->email); $this->command->warn('Password is "secret"'); } } } Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/permissions If you face any problem then please write a comment or give some suggestions for improvement. Thanks...
Laravel5.4 - Prevent Browser's Back Button Login After Logout
In this tutorials we are sharing with you one common web securite issue in laravel project. you are many time notice in laravel onece your are login in your laravel application and and then after logout from laravel application and then you press your browser back button. you realise your previes page is show which you are open befor logout. So, this is not good for securite perpouse, so how to fix this issue in laravel application with very simple way. when you are logout from laravel application then anyone try to press browser back button then they can not able to show any pages which we are open befor logout and they redirect on login screen. this way is very safe for security reason this type issue you can fix with laravel middleware. nothing do extra simple add some caching related code in middleware. so, when user logout from laravel application then your laravel application's cache create from stat to end. this issue arise due to browser caching system. if you visit any page in your browser the browser cache data from this page. so, simple follow this step and you can resolve this laravel security related issue step : 1 create new middleware you can also add this code in your current middleware which you are using for check login. but i create here new one for it. create one new middleware using this command. php artisan make:middleware DisablePreventBack step : 2 Configur middleware your new middleware is created this path app/Http/Middleware/DisablePreventBack.php so, open it and Configur your middleware like that... <?php namespace App\Http\Middleware; use Closure; class DisablePreventBack { /** * Handle an incoming request. * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate') ->header('Pragma','no-cache') ->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT'); } } step : 3 Regitration middleware [ADDCODE] Now you must be register this middleware. so, open app/Http/Kernel.php file and add your middleware in $routeMiddleware array variable into the last like that.. <?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { ........ ........ /** * The application's route middleware. * These middleware may be assigned to groups or used individually. * @var array */ protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'disablepreventback' => \App\Http\Middleware\DisablePreventBack::class, ]; } step : 4 Use this middleware in route Now how to use this middleware in your route like that... Route::group(['middleware' => 'disablepreventback'],function(){ Auth::routes(); Route::get('/home', 'HomeController@index'); }); We are hope this tutorials is helpfull to you...