n212
n212

Reputation: 607

How to push an array value into database with Laravel 6?

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?

Upvotes: 0

Views: 3322

Answers (1)

Danny Ebbers
Danny Ebbers

Reputation: 919

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.

Upvotes: 1

Related Questions