Laravel Eloquent Model Tutorial with example | All about Models in Laravel 10
A Laravel model represents and interacts with a database table in the application.
Using the Eloquent Model, you can perform many database-related operations such as create, update, read, and delete records.
Let’s explore the functionalities that can be performed using Laravel Eloquent Model in detail:
1. Create a Model
STEP 1: To create a new Model, Run the below command which will generate a new file in the 'app/Models' directory. So let's take an example of Product.
php artisan make:model Product
After successfully running the artisan command it creates the Model as Product.php
STEP 2: Open the Product Model in the following path app/Models/Product.php and this is the Structure of the model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
}
2. Table Name ( $table Property ) : give table name in the Product Model as shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $table = 'products';
}
3. Table Columns ( $fillable Property ): give table column names in the Product Model as shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
// ... your existing code
protected $fillable = [
'name',
'product_code',
'price',
'stock',
'is_active'
];
}
4. Attribute Casting ( $casts Property ) : give table columns casting in the Product Model as shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
// ... your existing code
protected $casts = [
'start_date' => 'datetime',
'end_date' => 'datetime:Y-m-d',
'is_active' => 'boolean',
];
}
5. Append Attribute ( $appends Property ) : append new attributes to eloquent the Product Model as shown below.
Suppose you want to get the Product Name and Product Code together and add this data to as column while getting the data using the Model.
You can achieve this by using $appends Property and Accessor in Laravel.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
// ... your existing code
protected $appends = ['name_code'];
public function getNameCodeAttribute()
{
return $this->name . ' ' . $this->product_code;
}
}
6. Set Primary Key Column ( $primaryKey Property ) : (If required only)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
// ... your existing code
protected $primaryKey = 'id';
}
7. Hidden Attribute ( $hidden Property ) :
The use of the $hidden property within an Eloquent model offers a powerful way to control the fields that are excluded from the model's JSON form when it's returned in responses.
By specifying an array of fields like 'created_at' and 'updated_at' within the $hidden property, these fields are automatically concealed from the retrieved data.
This code snippet hides the 'created_at' and 'updated_at' fields when retrieving data from the associated model, ensuring they're not included in the output.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
// ... your existing code
protected $hidden = [
'created_at',
'updated_at'
];
}
8. Accessors and Mutators
accessors and mutators allow you to manipulate the data of an Eloquent model when you retrieve or set values on its attributes.
Accessors:
Accessors are used to format or manipulate the data when it is accessed. They are defined by creating a method on the model with the attribute name in camel case followed by the word "Attribute" and prefixing it with 'get'.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
// ... your existing code
// Assume 'name' (product_name) is a column in the products table.
public function getNameAttribute()
{
return ucfirst($this->attributes['name']);
}
}
In this example, when you retrieve the name attribute, the getNameAttribute accessor will be automatically called, and it will return the value of name with the first letter capitalized. You can use this "Accessors" in many ways.
Usage:
// Using the accessor
$product = Product::find(1);
echo $product->name; // Output: Product one
Mutators:
Mutators are used to format or manipulate the data before it is saved to the database. They are defined by creating a method on the model with the attribute name in camel case followed by the word "Attribute", and prefixing it with 'set'.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
// ... your existing column names
// ... your existing column names
];
// Assume 'slug' is a column in the products table.
public function setNameAttribute($value)
{
$this->attributes['name'] = strtoupper($value);
$this->attributes['slug'] = Str::slug($value);
}
}
In this example, the 'setNameAttribute' mutator will be automatically called before saving the 'slug' attribute data to the database and also changing the Product Name to Uppercase. It will generate a slug from the name attribute using Laravel's Str::slug method.
Now, you can use this model as follows:
// Example usage
$product = new Product;
$product->name = 'Awesome Product Name';
$product->save();
// The 'slug' attribute in the database will be automatically generated as 'awesome-product-name'
This way, you ensure that the slug attribute is populated based on the name attribute, making it URL-friendly for use in routes or links.
9. Laravel Eloquent Model Relationships
The eloquent relationship is split into:
- One to one
- One to many
- Many to many
- Has One Through
- Has_many Through
- One to One (polymorphic)
- One to Many (polymorphic)
- Many to Many (polymorphic)
You can get a complete guide on each relationship in the Complete Guide to the Eloquent Relationship.
I hope this helps you. Thanks for reading.