0

I want to add multiple values to a names column in my database. I've set the casts in the model to make this an array.

Controller

public function add() {
   $id = 1;
   $db = Article::find($id)->first();
   $start = $db->names;
   $db->names = array_push($db->names,'value');
}

Model

class Article extends Model
{
    protected $casts = [
        'names' => 'array'
    ];
}

This gives me an error message back Indirect modification of overloaded property App\Article::$names has no effect

How do I push (or remove) a value to the array in my database?

1

1 Answer 1

1

This happens because the $db->name is not an array, it is an laravel eloquent magic property.

You can either

array_push($start, 'newvalue');
$db->names = $start;
$db->save();

Or use indeed a setter, laravel also offers a "Magic" method of defining model setters, as in mutators

See: https://laravel.com/docs/6.x/eloquent-mutators#defining-a-mutator

I would also consider, not using array push, if it's just a flat array

$originalArray = $db->names;
$originalArray[] = 'Additional Value';
$db->names = $originalArray;
$db->save();

Would work the same, and might be easyer to read.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, thank you for your answer. I tried the first thing and it seems to store the number "2" instead of pushing it to the existing array in the database. Do you know why this is?
Yes, i actually worked from your sample. But array_push does not return the new array but, the actual number of elements on the array. The first argument is modifed by reference: see php.net/manual/en/function.array-push.php
What about using array_merge instead? $db->names = array_merge($db->names, ['newValue']);
@Arcesilas Thank you, that solution worked as well.
Even more fancy, if you would have php 7.4 $db->names = [...$db->names, 'newValue'] laravel-news.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.