Laravel
Resources

Resources in Laravel

There are many way to access resources in Laravel. Below is a list of the most common ways I used to access resources.

Resource Controller

The resource controller is a great way to quickly create a controller with all the CRUD methods. It is also a great way to quickly create a route for all the CRUD methods.

Route::resource('posts', 'PostController');
php artisan make:controller PostController --resource

Above command will create a controller with all the CRUD methods. It will also create a route for all the CRUD methods.

Route Model Binding

By using route model binding, you can access the model directly in your controller method without the need to write a query to fetch the model.

php artisan make:controller PostController --resource --model=Post

Above command will create a controller with all the CRUD methods with model being injected into the controller method.

Model Policy

Model policy is a great way to control the access to the model. It is also a great way to control the access to the model in the controller.

Example condition:

  • Only the owner of the post can update the post.
  • Only the owner of the post can delete the post.

With above condition, you can create a policy for the Post model and set the condition in the policy. This way it will be easier to maintain the condition and controller will be cleaner from the above condition.

Below is an example of how to create a policy for the Post model.

php artisan make:policy PostPolicy --model=Post

Above command will create a policy for the Post model.

To use the policy, you need to register the policy in the AuthServiceProvider.

app/Providers/AuthServiceProvider.php
use App\Models\Post;
use App\Policies\PostPolicy;
 
/**
 * The policy mappings for the application.
 *
 * @var array
 */
protected $policies = [
    Post::class => PostPolicy::class,
];

Then you can use the policy in the controller.

app/Http/Controllers/PostController.php
public function __construct()
{
    $this->authorizeResource(Post::class, 'post');
}

For more information, please refer to Laravel Policy (opens in a new tab).