laravel policies tutorial Beginners (2019)

Laravel Policies

Hi, Guys Today we are going to set up Laravel policy for User access Control.

So, to begin with, we need to have a laravel project, If you are starting from scratch then you should check here Create Laravel Project.

However, if you have your localhost setup you can create a project using this command in terminal (commander) in Windows.

composer create-project --prefer-dist laravel/laravel blog

composer create-project --prefer-dist laravel/laravel blog

Now if you have laravel project. You need to have user registration working (comes default from laravel out of the box). To set it up to follow below-given steps.

1.run this command

php artisan make:auth

2. If the command runs fine then ok, otherwise you might face an error.

About string too long to fix this error copy below the given line of code in your project in App/Providers/AppServiceProvide.Under boot function. Check Here

use Illuminate\Support\Facades\Schema;
 
public function boot()
{
    Schema::defaultStringLength(191);
}

 3. Now run these commands one by one

php artisan migrate
php artisan make:auth

Migrate command will create tables in the database and make auth will create view and controller for login and register functionality. If you have localhost setup then put database credentials in

.env file in you project root folder,Before running above commands.

Let’s Get Started With Policies

To generate policy folder we need to run below-given the command.

php artisan make:policy PostPolicy

To make policy with crud functions in it by default you can run

php artisan make:policy PostPolicy --model=Post

After running the command you will get Policies folder in your project.


Now go to App/Providers/AppServiceProvider file in your project.

code in this file should look something like this.


 'App\Policies\PostPolicy',
    ];
    
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        
        $this->registerPolicies();
 
        Schema::defaultStringLength(191);
    }
}

Now in the above code.we are setting Post Model with Post Policy as given in array ($policies). In this array, we can add more Policies.

$this->registerPolicies();

RegisterPolicies function registering our policy with laravel.

In your App/Policies/PostPolicy file. Add below-given code which returns a true value.

namespace App\Policies;
 
use App\User;
use App\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Auth;
 
 
/**
     * Determine whether the user can create posts.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
       return true;
    }

In the above-given function, you can add your code about the user and return a true and false value. Depending on this true or false value your user access will work.


Above function returns “true”. That means User can create Post. Note that we are including User and Post Model In above code.


use App\User;
use App\Post;


Now in post controller. We can check if the user can create a post or not.

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
use Illuminate\Support\Facades\Auth;
 
use Redirect;
 
use Illuminate\Support\Facades\Gate;
 
use Session;
 
use App\Models\Post;
 
use App\User;
 
class PostController extends Controller
{
     public function store(Request $request, User $user,Post $post)
        {  
        if ($user->can('create', $post)){
            echo"Works";
        }
}

Now above code will output works. Because we are getting “True” as return from our Policy Remember. If we get false this code will not print “works”.

That’s it you have completed Policy and got it working. In the above code instead of “Works”, You can write code that you want if the user can create a post then only that code will work. And App/Policies/PostPolicy.php file you can set up conditions for the user.

Apply filters like this

//displaying post by user in add post page admin on routes
    Route::post("/admin/post/get",[
        'uses'=>'PostController@index',
    ])->middleware('can:create,App\Post');;
 
 
//if user can create post (author,admin) on controller
       if ($user->can('create', $post)){
             //do something
       }
//on blade.php files
@can('create', App\Post::class)
      //do something
@endcan