Laravel 11 New Model::casts() Method Example

By Hardik Savani September 4, 2024 Category : Laravel

Laravel 11 Model casts Method

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

<?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...

Shares