Learn How to Use Laravel Enum Casting

Understand how to implement enum model attribute casting in Laravel 9 for efficient data handling.

If you’re looking to use the enum data type in Laravel, you can do so easily with the help of enum model attribute casting. In this post, we’ll walk you through a step-by-step example to show you how to use enums in Laravel and cast them to a model attribute.

First, you’ll need to create a migration with a string column called "status" and a default value of "pending". Then, you can create a model and set the cast to your enum class. With this approach, you won’t have to create a new migration every time you want to add a new enum value to your table.

Laravel 9 has introduced enum model attribute casting, which makes it easier than ever to use enums in your application. With the help of an enum class and model casting, you can easily set up your table with specific enum values.

In this example, we’ll guide you through the process of creating a migration with a string column, creating a model with a cast to your enum class, and creating an enum class with specific values. Follow along with our step-by-step example to learn how to use Laravel enum attribute casting today.

Step 1: Install Laravel

If you haven’t already created a Laravel app, run the following command to install Laravel:

composer create-project laravel/laravel example-app

It will install new laravel app inside example-app folder. For further commands, go inside the example-app folder. There are many other ways to install the laravel application. Click on this link to visit Laravel installation documentation.

Step 2: Create Laravel Migration

Create a migration for the "enquiries" table with name, email, phone and status columns, as well as a model for the enquiries table. run the following command to create migration:

php artisan make:migration create_enquiries_table

Update the migration file with the following code:

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('enquiries', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->bigInteger('phone');
            $table->string('status')->default('pending');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('enquiries');
    }
};

Now, we are ready with our migration script. Run the following command to create the "enquiries" table:

php artisan migrate

Note that, we created the table with "status" value as "pending" by default.

Step 3: Create Enum Class

Create the Enums folder and EnquiryStatusEnum.php class inside the Enums to define all enum values as follows:

namespace App\Enums;

enum EnquiryStatusEnum: string {
    case Pending = 'pending';
    case InProgress = 'in-progress';
    case Closed = 'closed';
}

Step 4: Create Model

Now, we need a model file for our enquiries table. To create a model, run the following command:

php artisan make:model Enquiry

It will create Enquiry.php file inside the app/Models folder. Change the model file as follows:

namespace App\Models;

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

class Enquiry extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'email', 'phone', 'status'
    ];

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

Here, we defined a $casts variable, which will cast the status variable with EnquiryStatusEnum class.

Step 5: Create Controller

Now, create a controller file using the following command:

php artisan make:controller EnquiryController

It will create the EnquiryController.php file inside the app/Http/Controllers folder. Write the following code inside index() method to create item records with an array and access as an array:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Enquiry;
use App\Enums\EnquiryStatusEnum;

class EnquiryController extends Controller
{
    public function index()
    {
        $input = [
            'name' => 'Test User',
            'email' => 'test@example.org',
            'phone' => 6358465465
            'status' => EnquiryStatusEnum::Active
        ];

        $enquiry = Enquiry::create($input);

        dd($enquiry->status, $enquiry->status->value);
    }
}

In above code, we have added a new entry inside the enquiries table and right after that we displayed the enquiry status.

Step 6: Create Route

To create a route for testing our code, add the following lines to routes/web.php file:

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

Route::get('enquiry', [EnquiryController::class, 'index']);

Step 7: Run the Laravel app

To run the laravel app, use the following command:

php artisan serve

Open your web browser and enter the following URL to view the app output:

http://localhost:8000/enquiry

You can see the database output and print variable output:

App\Enums\EnquiryStatusEnum {#1781
    name: "InProgress"
    value: "in-progress"
}

in-progress

You can see the database output, which is showing casted values from EnquiryStatusEnum. And second parameter is value output, which is showing it’s corresponding string value "in-progress".

With these simple steps, you can easily use enum in Laravel without the need for constant migrations.

Install React JS with Laravel Breeze

Guide to installing Laravel Breeze with React JS scaffolding via Inertia for building modern applications.

In this React JS tutorial, we learn to install Laravel Breeze with React JS over Laravel Application. Laravel Breeze come equipped with out-of-the-box scaffolding for new Inertia applications, making them the quickest and easiest way to get your Inertia project off the ground with React Js.

For this post, we are using Laravel Breeze. This minimal implementation includes login, registration, password reset, email verification, password confirmation, and a basic “profile” page for updating user information.

Laravel Breeze comes equipped with simple Blade templates styled with Tailwind CSS. However, if you prefer to scaffold your application using React JS and Inertia JS, Laravel Breeze can do that too.

In addition to being an excellent starting point for a new Laravel project, Laravel Breeze is also a great choice for projects that want to elevate their Blade templates using Laravel Livewire.

Install laravel project and setup database

First install a fresh new Laravel application from the composer using the following command,

composer create-project laravel/laravel inertia-react

It will create the laravel project folder named inertia-react .

Now, you have to connect the laravel app to the database. Go inside this folder and open .env to change the database connection details as follows,

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password

After changing the connection details, run all migrations for the project using the following command,

php artisan migrate

Install Laravel Breeze over Laravel

Once you ready with the Laravel installation, you can proceed with Laravel Breeze installation using Composer using the following command,

composer require laravel/breeze --dev

Once you’ve installed the Laravel Breeze package using Composer, it’s time to run the breeze:install Artisan command as follows,

php artisan breeze:install

This command will publish all the necessary authentication resources, including views, routes, controllers, and more, directly to your application.

Laravel Breeze publishes its code directly to your application, giving you complete control and visibility over its features and implementation. This allows you to easily customize and tailor the authentication experience to fit your unique needs.

If you want to use an Inertia stack with React JS in your Laravel Breeze application, simply specify “react” as your desired stack when running the breeze:install Artisan command as follows,

php artisan breeze:install -react

Once the scaffolding is installed, be sure to compile your application’s frontend assets to ensure proper functionality:

npm install && npm run dev

With the initial setup complete, it’s time to test your application’s authentication functionality. Simply navigate to the /login or /register URLs in your web browser to get started.

All of Laravel Breeze‘s routes are defined in the routes/auth.php file, making it easy to modify or customize the authentication routes as needed.

Laravel Middleware Explained: What It Is & How to Create One

Learn what middleware is in Laravel, why it’s essential, and how to create custom middleware for handling requests efficiently. Step-by-step guide included.

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. It’s best to envision middleware as a series of “layers” for HTTP requests that must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

For example, Laravel includes a middleware that verifies the authenticity of the user of your application. If the user is not authenticated, the middleware will redirect the user to your application’s login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

To perform different tasks, we can develop many middlewares besides authentication. For example, a logging middleware might log all incoming requests to your application. 

Laravel framework has included many middlewares, including middleware for authentication and CSRF protection. All of these middlewares are located in the app/Http/Middleware directory.

Create a custom middleware

To create a middleware, we can use the following command,

php artisan make:middleware <middleware-name>

For example, if we want to create a middleware for checking transactions, we can run the following command,

php artisan make:middleware CheckTransaction

 After successful execution of the command, a middleware class will be created under the app/Http/Middleware directory.

In this class, we can define methods to check transactions. If the transaction is not completed, we can redirect the user back to the failed transaction page. However, on the successful transactions, we can allow users to proceed to the next page.

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class CheckTransaction
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->input('status') !== 'completed') {
            return redirect('transaction-failed');
        }
 
        return $next($request);
    }
}

As you can see, if the transaction status does not set to “completed”, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application.

To pass the request deeper into the application (allowing the middleware to “pass”), you should call the $next callback with the $request.

What Are ORM Frameworks? A Beginner’s Guide

Understand what ORM (Object-Relational Mapping) frameworks are, how they work, and why they are essential in modern web development.

ORM is a short form of Object Relational Mapping. ORM framework is written specifically in OOP (object-oriented programming) language (like PHP, C#, Java, etc…). It is like a wrapper around a relational database (like MySQL, PostgreSQL, Oracle, etc…). So, ORM is basically mapping objects to relational tables.

What does an ORM framework do?

The ORM framework generates objects (as in OOP) that virtually map the tables in a database. So, any programmer could use these objects to interact with the database without writing an optimized SQL code.

For example:

We have 2 tables in a database:

  • Products
  • Orders

The ORM framework would create 2 objects corresponding to the above tables (like products_object and orders_object) with little configuration, which will handle all the database interactions. So, if you want to add a new product to the products table, you would have to use the products_object and save() method like below,

product = new products_object("Refrigerator","Electronics");
product.save();

You can see, how much easier an ORM framework can make things. No need to write any SQL syntax. And the application code would be very clean.

Some other advantages of using ORM frameworks

1. Syncing between OOP language and the relational database data types is always creating a problem. Sometimes variable data types have to be converted properly to insert into the database. A good ORM framework will take care of these conversions.

2. Using an ORM will create a consistent code base for your application, because it is not using any SQL statements in the code. This makes it easier to write and debug any application, especially if more programmers are using same code base.

3. ORM frameworks will shield your application from SQL injection attacks since the framework will be filtering the data before any operation in the database.

4. Database Abstraction; Switching databases for the application is easier as, ORM will take care of writing all the SQL code, data type conversions etc …

When to use an ORM framework?

An ORM framework becomes more useful as the size and complexity of the project increases. An ORM framework may be overkilling an application on a simple database with 5 tables and 5-6 queries to be used for the application.

Consider the use of ORM when:

  • 3 or more programmers are working on an application.
  • Application database consists of 10+ tables.
  • The application is using 10+ queries.

About 80-90% of application queries can be handled by the ORM generated objects. It is inevitable that at some point straight SQL query is required, which can’t be handled by ORM generated objects.

In fact, ORM frameworks often have their own *QL query language that looks a lot like SQL. Doctrine, a popular PHP based ORM framework has DQL (Doctrine Query Language) and the very popular Hibernate (used in the Java and .Net world) has HQL. Going even further, Hibernate allows writing straight SQL if need be.

ORM Frameworks for PHP programmers

  • CakePHP, ORM, and framework for PHP 5
  • CodeIgniter, a framework that includes an ActiveRecord implementation
  • Doctrine, open source ORM for PHP 5.3.X
  • FuelPHP, ORM, and framework for PHP 5.3. Based on the ActiveRecord pattern.
  • Laravel, a framework that contains an ORM called “Eloquent” an ActiveRecord implementation.
  • Maghead, a database framework designed for PHP7 includes ORM, Sharding, DBAL, SQL Builder tools etc.
  • Propel, ORM and query-toolkit for PHP 5, inspired by Apache Torque
  • Qcodo, ORM, and framework for PHP 5
  • QCubed, A community-driven fork of Qcodo
  • Redbean, ORM layer for PHP 5, creates and maintains tables on the fly
  • Yii, ORM, and framework for PHP 5. Based on the ActiveRecord pattern.
  • Zend Framework, a framework that includes a table data gateway and row data gateway implementations. ZendDb