Laravel 11 New Model::casts() Method Example
September 4, 2024
Category : Laravel
In this short article, I will teach you how to use model casts() method in laravel 11 framework.
In Laravel 11, you can define casts as a method in a model. Laravel 11 supports both as a property and as a method. You can now use the `casts()` method to easily define casting in Laravel 11.
Let's see a simple example code of it.
app/Models/Product.php
Read Also: Exception/Error Handling in Laravel 11
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Enums\ProductStatus;
class Product extends Model
{
use HasFactory;
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'name', 'body', 'status'
];
/**
* casts define as Property
*/
protected $casts = [
'status' => ProductStatus::class
];
/**
* casts define as method (Right way in Laravel 11)
*/
protected function casts(): array
{
return [
'status' => ProductStatus::class,
];
}
}
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
Subscribe me on: Youtube
We are Recommending you
- How to Customize Default Middleware in Laravel 11?
- How to Register Schedule Command in Laravel 11?
- Laravel 11 New a Health Check Route Example
- How to Create Custom Middleware in Laravel 11?
- How to Publish Broadcasting Channels Route File in Laravel 11?
- How to Create and Use Traits in Laravel 11?
- How to use new Dumpable Trait in Laravel 11?
- How to Publish API Route File in Laravel 11?
- How to Create and Use Enum in Laravel 11?
- How to Publish Config Files in Laravel 11?
- How to Create Interface in Laravel 11?
- How to Create Custom Class in Laravel 11?
- How to Publish the lang Folder in Laravel 11?
- What’s New in Laravel 11: New Features and Latest Updates