Understanding php artisan make: controller PostController --resource --model=Post in Laravel

Glory OpeoluwaGlory Opeoluwa
2 min read

When working on Laravel applications, organizing your logic into controllers is a crucial part of adhering to the MVC (Model-View-Controller) pattern. One of Laravel’s most powerful Artisan commands for speeding up development is:

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

What Does the Command Do?

This command generates a resource controller named PostController and links it to the Post model. It automatically includes boilerplate methods needed for building a full CRUD (Create, Read, Update, Delete) feature.

Breakdown of the Command

  • php artisan: Invokes Laravel's command-line tool, Artisan.

  • make:controller: Tells Laravel to generate a new controller.

  • PostController: The name of the controller you want to create.

  • --resource: Automatically adds the 7 standard methods:

    • index() – List all posts

    • create() – Show form to create a post

    • store() – Save a new post

    • show($post) – Show a single post

    • edit($post) – Show form to edit the post

    • update($post) – Update the post in the database

    • destroy($post) – Delete the post

  • --model=Post: Links the controller to the Post model. This enables route model binding, where Laravel automatically fetches the model instance based on the route parameter.

Example Use Case

After running the command, Laravel will create:

app/Http/Controllers/PostController.php

With pre-filled methods like:

public function index()
{
    $posts = Post::all();
    return view('posts.index', compact('posts'));
}

You can now quickly build features like listing all posts, displaying a post form, editing posts, and more, without starting from scratch.

Setting Up Routes

To make this controller work, you should register it in your routes/web.php file like this:

Route::resource('posts', PostController::class);

This single line gives you all the RESTful routes you need:

  • GET /posts

  • GET /posts/create

  • POST /posts

  • GET /posts/{post}

  • GET /posts/{post}/edit

  • PUT /posts/{post}

  • DELETE /posts/{post}

Why It Matters

Using --resource and --model:

  • Saves time

  • Encourages clean, RESTful code

  • Follows Laravel best practices

  • Prepares your app for scalability and maintenance

In Conclusion

This command is a game-changer for Laravel developers. Whether you're building a blog, an admin dashboard, or any CRUD-based feature, this one-liner jumpstarts your controller logic and keeps your codebase organized. If you're learning Laravel, I highly recommend practicing with this command, creating controllers for your models, and exploring the flow from routing to views.

0
Subscribe to my newsletter

Read articles from Glory Opeoluwa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Glory Opeoluwa
Glory Opeoluwa