Start a Project

A Beginner’s Guide to use Laravel Casting with Examples

Hello Everyone in this blog, we’ll learn Laravel casting with examples, step by step.

Working with Laravel’s Eloquent ORM, you might come across situations where you want to treat some attributes of your models as specific data types instead of raw strings. Laravel provides a feature called “casting” that allows you to automatically transform attribute data into desired datatypes. casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Laravel’s casting feature saves you from manual type conversions and provides a cleaner and more maintainable codebase.

By defining the $casts property within your model, you can instruct Laravel to automatically convert those attributes to desired data types. Laravel supports various casting types, including integers, floats, booleans, dates, arrays, and more.

Step 1: Install Laravel Application

Let’s create a fresh new Laravel project. It’s optional if you have already created then you may go ahead.

Step 2: Create a Model

Let’s create a simple Eloquent model that represents a book. Run the following command to generate the model and migration:

This command will create a Book model file inside the app/Models directory and a migration file in thedatabase/migrations directory.

Step 3: Define the Migration

Open the generated migration file in the database/migrations directory and define the table schema for the books table.

Run the migration to create the books table:

Step 4: Define Casting in the Model

Now, let’s open the app/Models/Book.php file and define the casting for the pages and published_at attributes:

With this configuration, Eloquent will automatically convert the pages attribute to an integer and the published_at attribute to a date whenever you access or set them.

Step 5: Create and Use the Book Model

Now that we have our model and casting defined let’s use it to insert and retrieve data.

 

We created a simple Eloquent model for books and determine how to define casting for attributes. I hope you will like the Tutorial and it will help you to learn Laravel Casting. Please comment below if you have any questions.

You can also hire laravel developers to build your custom solutions on laravel. For exploring the available extensions for Bagisto, you can check out the bagisto extension marketplace.

Exit mobile version