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


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 postscreate()
– Show form to create a poststore()
– Save a new postshow($post)
– Show a single postedit($post)
– Show form to edit the postupdate($post)
– Update the post in the databasedestroy($post)
– Delete the post
--model=Post
: Links the controller to thePost
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.
Subscribe to my newsletter
Read articles from Glory Opeoluwa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
