Laravel Authorization by Example

Now we will creating the POST model and controller with migration

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

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

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

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

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

Now you can run following command to populate the data

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

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

Finally you can define update action in the controller and view

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *