Retrieve Value from Field in Laravel Cast Array - laravel

I have a table named settings, in it, there are several columns, id,company_id, key, value.
In my Laravel model for Setting, I have the following cast:
protected $casts = [
'value' => 'array',
];
But when I go to retrieve data that has been stored, I can't.
For example, I have a record with the following value: "{\"default_remit_address\":\"2395\"}"
And when I go to retrieve the record in a Blade, it does pull it up correctly, but I'm not sure how to grab a specific value from the value field (like default_remit_address).
If I print the return "{{$settings->value}}" directly in the Blade, this is what I get:
{"default_remit_address":"2395"}
So how can I go one level deeper?

As this json object is being cast to an Array, you can just use regular array syntax to access it's contents.
$default_remit_address = Settings::find(1)->value['default_remit_address'];
or in your blade template
{{ $settings->value['default_remit_address'] }}

Related

Laravel read multiple image path from Table

I'm having a hard time to read multiple file paths from my product tables in laravel.
I'm using Voyager as my admin interface, I have a multiple file upload that saves my path image in a field, when i query the table i get these result:
how do i read the photo field?
Already tried:
json_decode($product->photo,true) and it says "htmlspecialchars() expects parameter 1 to be string, array given"
with #foreach ($product->photo as $img) it gives me "Invalid argument supplied for foreach() "
photo column must be defined as JSON in its migrations file.
$table->json('photo');
And cast it to array in Product Model class:
protected $casts = [
"photo" => "array"
];
Now you will access photo as array and do what you want.

Has laravel 7 model a way to get list of all columns?

Has laravel 7 model a way to get list of all columns ?
I found and tried method
with(new ModelName)->columns
but it returns empty string.
I do not mean $fillable var of a model.
Thanks!
If you just want a reliable way to pull the list of attributes from any given instance no matter the state, and assuming the table structure isn't changing often, the path of least resistance might be to set a defaults attributes array to ensure the attributes are always present.
e.g.
class Fish extends Model
{
protected $attributes = [
'uuid' => null,
'fin_count' => null,
'first_name' => null,
];
}
$fishie = app(\Fish::class);
will then result in an instance of Fish with uuid, fin_count, and first_name set. You can then use $fishie->attributes or $fishie->getAttributes() to load the full set.
Assuming the structure doesn't change a lot, setting the attributes on the model like this will save you a database query every time you want to reference the list. The flip side is that instances change from not having the attributes unless explicitly defined to always being present, which may have implications in the project.
Here's the documentation for default attributes:
https://laravel.com/docs/master/eloquent#default-attribute-values

Laravel Array to string conversion error while updating database

I want to update a totcosty field in the User table but it is throwing this error everytime and it is not updating the field
this is the function for execution:
public static function cost(){
$user = User::find($user_id);
$total = Helper::totcost();
// dd($tot_amt);
$user->totcosty = $total;
$user->save();
}
array to string means you are sending an array to the database but db will not accept it you have to explode() the array before sending it to db...
Hope it will help!
If you really want to store an array in some table field, then better declare it as a JSON field. For this, your DB should have support for JSON type columns.
See here how to do this.
Once this is done, you can save arrays in that column, you can assign an array value to the model property and laravel will convert it to JSON while saving and also it will be converted to array while retrieving.

laravel get data without applying casts

I am doing
Model::get()->toArray()
to get all the data from my table but the model has a cast on the dates.
protected $casts = ['date' => 'datetime:D, M d Y'];
I want to be able to get all the data without applying the cast and just the original datetime format. Is there a way to control when the cast is applied.
Laravel 7+
As Sam mentioned for Laravel 7+ you can use:
$model->getRawOriginal('created_at')
You can get all attributes as they are, by using
Model::get()->transform(function ($item) {
return $item->getOriginal();
}))->toArray();
Also can use getOriginal() as
$model->getOriginal('created_at')
on any model to get the original value whenever it's needed.
Note : getOriginal() will include all the $hidden attributes of the model.
getOriginal('date') and getRawOriginal('date') return the unmodified values !
If you want to get the current value without cast, you can use getAttributes()['date']

Store True as 1 False as 0 using Laravel + Eloquent + Mysql

I have a value of true or false coming from an ajax post to the back end (laravel) and I want to store it as 1 or 0 in the mysql database. This is basically a checkbox or radio that I reach into the DOM and grab the value. I believe I should be able to add a mutator:
protected $casts = [
'active' => 'boolean',
];
This does pull the 1 and convert it to true, however it does not store true as 1.
The documentation does not say the cast will be performed both directions for boolean, however it does say the cast works both directions for array
Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:
I could convert to integer on the client, I guess I would prefer to do it on the back end. Any other thoughts? I will need this conversion on many tables. I am using laravel 5.2
I believe you only need to be sure that your database column type is either boolean or tinyint.
Edit:
However, you can use a Mutator function in you model in order to convert it to int, like the following:
public function setActiveAttribute($value)
{
$this->attributes['active'] = (int) $value;
}

Resources