Laravel Authorization by Example

November 21, 2017

Now we will creating the POST model and controller with migration

php artisan make:model Post -m -c

So this will create the Post model and the PostController with migration file

Your migration file is located at database > migration and you can add the following code to create the Post table

  public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')
            $table->text('body')
            $table->unsignedInteger('user_id')

            $table->foreign('user_id')->references('id')->on('users')
            $table->timestamps();


        });
    }

Then you can run migrate command to create the POST table in the database

php artisan migrate

Now I am going to create seeder to populate some data to the Post table
You can run the following artisan command to make a seeder

php artisan make:seeder PostTableSeeder

Your seeder file is located at database>Seeds
Add the following code to PostTableSeeder.php to populate data

  public function run()
    {
        DB::table('posts')->insert(array(
        	 array('title'=>'POST A','body'=>'Some Text','user_id'=>1),
        	 array('title'=>'POST B','body'=>'Some Text','user_id'=>1),
        ));

    }

Now I am going to display all the post. First we will create the index action inside the PostController

Define router at routes\web.php

Route::get('post', 'PostController@index');

Now you can run following command to populate the data

php artisan db:seed --class=PostTableSeeder

Now lets look at how authorization works in laravel

I want to implement the policy such that only registered user can update the post if he is the owner of the post. when public user try to open the update page they should be directed to login page

You need to know Gate and Policies in Laravel to work with authorization
Gates determine if a user is authorized to do given action. This is defined in defined in the App\Providers\AuthServiceProvider class

public function boot()
    {
        $this->registerPolicies();

         Gate::define('update-post', function ($user,Post $post) {
            return $user->id == $post->user_id;
         });
         


    }

Then you need to define your route with middle-ware.

Route::get('post/update/{post}', 'PostController@update')
       	->name('update-post')
   		->middleware('can:update-post,post'); 

Finally you can define update action in the controller and view

  public function update(Post $post){
    
     return  view('post.update',['post' => $post]);

    }

And your view @ resources>view>post>update.blade.php

@extends('layouts.app')

@section('content')
Update Post
@if ($errors->has('name')) {{ $errors->first('name') }} @endif
@if ($errors->has('name')) {{ $errors->first('name') }} @endif
@endsection

Now you can test the page with this url http://localhost/dev/cc/laravel/user/public/post/update/1. If you have not logged in you will be directed to the login page