Laravel 9 Enum Model Attribute Casting Example

Hi All,

Today, laravel 9 enum attribute casting example is our main topic. this example will help you how to use enum in laravel 9. if you want to see example of how to use enums in laravel 9 then you are a right place. Here you will learn laravel 9 enum cast. follow bellow step for laravel 9 model cast enum.

If you want to use the enum data type for your table then you can create migration and take the enum data type and set enum value there. But when later you want to add one more enum value then you need to create again migration and change it. So, Laravel 9 introduces enum model attribute casting. You can create an enum class and set cast on the model. 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.

Laravel 9 Enum Model Attribute Casting Example

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

.medrectangle-4-multi-155{border:none!important;display:block!important;float:none;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

database/migrations/2022_07_11_141714_create_products_table.php

<?php

use IlluminateDatabaseMigrationsMigration;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateSupportFacadesSchema;

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 AppEnums;

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 AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

use AppEnumsProductStatusEnum;

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 IlluminateSupportFacadesRoute;

use AppHttpControllersProductController;

/*

|--------------------------------------------------------------------------

| 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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsProduct;

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

You can see database output and print variable output:

Database Output:

Laravel 9 Enum Model Attribute Casting Example

Output:

AppEnumsProductStatusEnum {#1250

name: "Active"

value: "active"

}

active

I hope it can help you…

Leave a Comment