• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Programming TagsLaravel

Attribute Casting with Laravel

Nov 8, 2021 Editorial Staff 1 Comment

Share
Tweet
Share
1 Shares

Laravel is well known MVC framework written in PHP programming language. Over the years, it became the next tool in your belt for a plethora of programmers.

When we work with MVC, we have to deal with models and attributes as this is the layer that makes contact with our database.

Oftentimes, we need to cast the values received from the attributes to another form. For example, you have a field called is_admin in the database table with optional values 0 or 1. But you need to receive this value as a boolean field. Although this may be true that you can write an if condition and check if the value is equal to 0 then false, or if the value is equal to 1 then it is true.

But wherever you use this attribute you need to convert to boolean by a condition. In other words, you need to write 100 conditions if you need to use this code in 100 places.

Attribute Casting is coming in very handy in this matter. It’s almost the same as accessors or mutators without requiring you to write any extra functions.

For this, Laravel has the $casts property. Let’s see how it works:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'price' => 'decimal:2',
        'status' => 'boolean',
        'is_available' => 'boolean'
    ];
}

Using this property the attributes are casted automatically, you will not need to make any changes manually or by a function.

The supported cast types are :

  • array
  • AsStringable::class
  • boolean
  • collection
  • date
  • datetime
  • immutable_date
  • immutable_datetime
  • decimal:<digits>
  • double
  • encrypted
  • encrypted:array
  • encrypted:collection
  • encrypted:object
  • float
  • integer
  • object
  • real
  • string
  • timestamp

Custom Casts

What if you are missing a cast option that is required for your next Laravel project. In that case, we can create our own cast option to suit our needs.

You may accomplish this by defining a class that implements the CastsAttributes interface.
Classes that implement this interface must define a get and set method.

The get method is responsible for transforming a raw value from the database into a casting value, while the set method should transform a casting value into a raw value that can be stored in the database.

For example, we will implement JSON cast type, which will decode from JSON and encode to JSON.

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return array
     */
    public function get($model, $key, $value, $attributes)
    {
        return json_decode($value, true);
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  array  $value
     * @param  array  $attributes
     * @return string
     */
    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

Once you have defined a custom cast type, you may attach it to a model attribute using its class name:

<?php

namespace App\Models;

use App\Casts\Json;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'options' => Json::class,
    ];
}

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Reader Interactions

Comments

  1. Frank says

    Feb 4, 2022 at 10:49 am

    that was good, thanks

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required



Search Here

Share

   



Hot topics

  • Replace “\n” with new line characters, using Notepad++ 15 views
  • Solution: windows photo viewer opens each time save a pic file 12 views
  • A Simple YouTube Video Downloader Script in PHP 10 views
  • How to Create PDF File From HTML Form Using Fpdf? 9 views
  • Simple PHP Shopping Cart 8 views
  • All Countries SQL file with Country Codes to Download 8 views
  • How to create and download a Zip file with PHP 8 views
  • How to set up GitHub SSH in Ubuntu with example 7 views
  • How to enter new line in Microsoft Teams? 7 views
  • Laravel Eloquent Select Column as Alias 7 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube























Copyright © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com