Laravel 11 Model::casts() Method Example

  Mar 2024
  ITSolutionsGuides
  Category: Laravel
Laravel 11 Model::casts() Method Example

Welcome To ITSolutionsGuides,

In Laravel 11, Model supports both the property and the method. The previous versions of the laravel only supports the property in the model. In Laravel 11 the model also supports the method. The Model::casts() method provides a convenient way to automatically cast attributes to desired data types. For instance, you can easily convert a string field to a boolean or JSON. This feature enhances data consistency and simplifies handling various data types within your application models.

using property ;

protected $casts = [
'status' => ProductStatus::class
];

using method ;

protected function casts(): array
{
return [
'status' => ProductStatus::class,
];
}


Lets see Laravel 11 Model::casts() Method Example with the detailed example.

Let's Start Coding

<?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 in Previous laravel versions
     */
    protected $casts = [
        'status' => ProductStatus::class
    ];
  
    /**
     * casts define as method (Right way in Laravel 11)
     */
    protected function casts(): array
    {
        return [
            'status' => ProductStatus::class,
        ];
    }
}

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides