"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Laravel Type Casting

Laravel Type Casting

Published on 2024-11-08
Browse:675

Laravel Type Casting

You can specify the data types for certain model attributes in Laravel by using type casting. It makes sure that Laravel automatically casts the attribute values to the designated types when you retrieve data from the database.

You Can Check Here For multiple types of Attribute Casting

By default, Laravel provides several cast types that you can use:

  1. Integer: The attribute will be cast to an integer.
  2. Real: The attribute will be cast to a float.
  3. Float: The attribute will be cast to a float.
  4. Double: The attribute will be cast to a double.
  5. String: The attribute will be cast to a string.
  6. Boolean: The attribute will be cast to a boolean.
  7. Object: The attribute will be cast to a PHP object.
  8. Array: The attribute will be cast to a PHP array.
  9. Collection: The attribute will be cast to a Laravel collection.
  10. Date: The attribute will be cast to a date (Y-m-d) format.
  11. DateTime: The attribute will be cast to a DateTime instance.
  12. Timestamp: The attribute will be cast to a Unix timestamp (integer).
 'boolean',
            'age' => 'integer',
            'data' => 'array',
            'created_at' => 'datetime',
        ];
    }

In this illustration, the created_at value will be converted to a DateTime instance, the age attribute to an integer, the data attribute to an array, and the is_admin attribute to a boolean.

Therefore, you can keep JSON tags data in a user table, but when you fetch the users, you can immediately transform them into a PHP array, which eliminates the need to create a tags table.

When working with attributes in your Laravel models, type casting makes it easier to deal with the desired data type without having to convert it every time you access or change an attribute’s value.


if you love the content and want to support more awesome articles, consider buying me a coffee! ☕️? Your support means the world to me and helps keep the knowledge flowing. You can do that right here: ? Buy Me a Coffee

Release Statement This article is reproduced at: https://dev.to/aj_c6413caf1a793de3a2163b/laravel-type-casting-44d0?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3