0
0
Laravelframework~5 mins

Model creation in Laravel

Choose your learning style9 modes available
Introduction

Models help you work with your database easily. They represent data tables as simple PHP classes.

When you want to save new data to the database.
When you need to get data from a database table.
When you want to update or delete records in the database.
When you want to connect related data tables together.
When you want to keep your code organized and clean.
Syntax
Laravel
php artisan make:model ModelName

This command creates a new model file in the app/Models folder.

ModelName should be singular and start with a capital letter.

Examples
Creates a model named Post to work with posts table.
Laravel
php artisan make:model Post
Creates a model named Comment for comments table.
Laravel
php artisan make:model Comment
Creates a Product model and a migration file to create the products table.
Laravel
php artisan make:model Product -m
Sample Program

This example shows a Book model with fillable fields. It creates a new book record and then prints all book titles.

Laravel
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    // The model automatically uses the 'books' table
    protected $fillable = ['title', 'author', 'year'];
}

// Usage example in a controller or route closure:

use App\Models\Book;

// Create a new book record
$book = Book::create([
    'title' => 'The Great Gatsby',
    'author' => 'F. Scott Fitzgerald',
    'year' => 1925
]);

// Get all books
$allBooks = Book::all();

// Output titles
foreach ($allBooks as $b) {
    echo $b->title . "\n";
}
OutputSuccess
Important Notes

Model names are singular, but Laravel assumes the database table is plural.

Use the -m option to create a migration file along with the model.

Always define $fillable to allow mass assignment safely.

Summary

Models represent database tables as PHP classes.

Use php artisan make:model ModelName to create a model.

Models make it easy to create, read, update, and delete data.