Skip to content

All topics  /  Laravel

How to Used Enum Model Attribute Casting in Laravel?

Laravel ·

Teams applying “How to Used Enum Model Attribute Casting in Laravel?” in a production project can use the related planning guide to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.

Hi dev,

Today's main topic is a laravel enum attribute casting example. You may learn how to utilise enum in Laravel by using this example. You've come to the right place if you want to see an example of how to use enums in Laravel. You may learn about laravel enum cast here. For the Laravel model cast enum, follow the steps below.

You can build a migration, take the enum data type, and set an enum value there if you wish to use the enum data type for your table. However, you must construct a new migration and make the necessary changes if you decide to add more enum values in the future. Therefore, enum model attribute casting is introduced in Laravel 9. You can set cast on the model and generate an enum class. You can see the below step by step example and learn from there.

In this example, first, we will create migration with string column "status" and default value will be "pending". Then we will create a model with a casting to set enum class. Then we will create enum class with specific values and use on model cast. so let's see simple example and learn it.

Step 1: Install Laravel


This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app	

Step 2: Create Migration

Here, we need create database migration for "products" table with name, body and status columns and also we will create model for products table.

php artisan make:migration create_products_table	

database/migrations/2022_07_11_141714_create_products_table.php

<?php

  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('body');
            $table->string('status')->default('pending');
            $table->timestamps();
        });
    }

  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};	

Then run migration command to create items table.

php artisan migrate	

Step 3: Create Enum Class

In this step, we will create ProductStatusEnum.php class and define all enum values. let's create model and update following code:

app/Enums/ProductStatusEnum.php

<?php

  
namespace App\Enums;

 
enum ProductStatusEnum:string {
    case Pending = 'pending';
    case Active = 'active';
    case Inactive = 'inactive';
    case Rejected = 'rejected';
}	

Step 4: Create Model

In this step, we will create Product.php model with cssting. let's create model and update following code:

php artisan make:model Product	

App/Models/Product.php

<?php

  
namespace App\Models;

  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Enums\ProductStatusEnum;

  
class Product extends Model
{
    use HasFactory;

  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'name', 'body', 'status'
    ];

  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $casts = [
        'status' => ProductStatusEnum::class
    ];
}	

Step 5: Create Route

In third step, we will create one route for testing. so create one route here.

routes/web.php

<?php

 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

   
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

     
Route::get('product-test', [ProductController::class, 'index']);	

Step 6: Create Controller

In this step, we will create ProductController file and write index() method to create item records with array and access as array.

app/Http/Controllers/ProductController.php

<?php

  
namespace App\Http\Controllers;

  
use Illuminate\Http\Request;
use App\Models\Product;

  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $input = [
            'name' => 'Gold',
            'body' => 'This is a Gold',
            'status' => ProductStatusEnum::Active
        ];

  
        $product = Product::create($input);

  
        dd($product->status, $product->status->value);

  
    }
}	

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve	

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/product-test	

Output:

App\Enums\ProductStatusEnum {#1250 
  name: "Active"
  value: "active"
}
active