Premium Courses

Learn practical web development building multi user SEO blog app in Laravel. A Journey from localhost to live server.

Learn the fastest growing and high in demand React Js in short period of time along with ES6. Build a Newsapp while learning.

A complete beginners guide to Web Development. Master the art of building Responsive web pages with this course. Learn to code from scratch!

Authorization and Policies in Laravel



Asked by Anonymous 9 months ago

How to use authorization with policies in laravel?


Answered by Ryan Dhungel 9 months ago

Using Authorization with Policies in Laravel

The code is taken from Intermediate Level Tutorial from Laravel Documentation:


Our aim is to make sure that the user deleting the task is actually the user who created it.
The task user id and the logged in user id should match.


Task controller destroy method

public function destroy(Task $task)
{
$task->delete();
return redirect()->route('tasks.index');
}


Create task policy using artisan command

art make:policy TaskPolicy

Policies/TaskPolicy.php

<?php

namespace App\Policies;

use App\User;
use App\Task;
use Illuminate\Auth\Access\HandlesAuthorization;

class TaskPolicy
{
use HandlesAuthorization;

public function destroy(User $user, Task $task)
{
return $user->id === $task->user_id;
}
}

 

Register the policy that we have just created


App/Providers/AuthServiceProviders.php

protected $policies = [
Task::class => TaskPolicy::class,
];


This is how we can use authorization with policies in laravel.



Add your answer

×

Hi! Please sign in to add your answer.