How to use the @can blade directive in Laravel

Blade directives are shortcut codes in Laravel blade templating engine that help to implement basic PHP control structure. For example loop and conditional statements. They make a code snippets clean and easier to understand. Let us discuss about the @can directive in this article.

The @can directive helps perform authorization checks within templates. It helps to conditionally display content based on a user’s ability to perform certain actions. Let’s go through the main steps on how to use the @can directive in Laravel.

Use of @can blade directive

We can open the @can block in our Laravel blade file and pass the permission or action we want to check. Consider the code snippet shown below.

@can('delete', $car)
    // Content that should be displayed if the user has the 'delete' ability on $car
@else
    // Content to display if the user does not have the 'delete' ability on $car
@endcan

Here, the blade directive checks if the logged in user has the ability / right to delete a car’s details from the database. If yes, it deletes the car and performs the corresponding action. Otherwise it displays the error message or content of the user cannot delete.

Therefore, inside the can loop we can pass the action or the button to delete the car’s details for a specific user. For example, consider the code snippet below.

@can('delete', $car)
    <a href="{{ route('cars.delete', $car) }}">Delete Car Data</a>
@else
    <p>You do not have permission to delete this car's data.</p>
@endcan

The @can blade directive greatly simplifies authorization, and permissions set up in a Laravel application. The simple loop handles the entire authorization logic and conditionally renders elements to users who are authorized to perform such actions.