Creating a Model in Laravel
Laravel makes it very easy to create a new Model.
A Model represents the M part of the MVC (Model-View-Controller) architecture.
It is a PHP class that maps to a database table and performs Eloquent ORM operations.
Step 1: Create a New Model
Let's say you are building a Blog Application. Every blog application has posts, so you'll first create a Post
model.
Open your Terminal or Command Prompt, navigate to your Laravel project root, and run:
-
-m
generates a migration file. -
-r
generates a resourceful controller.
After running the command, you'll notice:
-
A new
Post.php
model is created under theApp\Models
directory (in older Laravel versions, underApp
directly):
-
A new migration file is created under
database/migrations/
(something like2025_04_29_000000_create_posts_table.php
):
-
A new resourceful controller is created under
App\Http\Controllers
:
Step 2: Define Table Structure
Now, let's update the migration file to include fields that posts typically need, such as title
and body
.
Edit the up()
Method in your migration like this:
-
title
: A short text for the post's title (usingstring
). -
body
: A longer text for the post's content (usingtext
).
Step 3: Run the Migration
Now, create the database table by running:
This command will generate the posts
table in your database.
Summary
-
You created a Model, a Migration, and a Resourceful Controller.
-
You updated the migration to define the
posts
table fields. -
You ran the migration to create the actual database table.
Now you're ready to start working with posts in your Laravel application!