How to cast string into int in laravel model?

Member

by rollin , in category: PHP Frameworks , 4 days ago

How to cast string into int in laravel model?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 3 days ago

@rollin 

To cast a string into an integer in a Laravel model, you can use the Laravel Eloquent's mutators.


In your model, you can define a mutator method that will automatically cast the string into an integer before saving it to the database. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class YourModel extends Model
{
    protected $fillable = ['your_attribute'];

    public function setYourAttributeAttribute($value)
    {
        $this->attributes['your_attribute'] = (int) $value;
    }
}


In this example, your_attribute is the attribute that you want to cast to an integer. The setYourAttributeAttribute method will be called automatically when you try to set the value of the your_attribute attribute of the model. It will cast the value to an integer using (int) $value.


Now, when you set a value for the your_attribute attribute of the model, it will be automatically cast to an integer before saving it to the database.


You can also define an accessor method to cast the integer back to a string when retrieving it from the database if needed.