D. Pachauri
D. Pachauri

Reputation: 244

Laravel throwing error on create method

$permission = new Permission();
$permPost = $permission->create([ 
    'name'        => 'post',
    'slug'        => [          // pass an array of permissions.
        'create'     => true,
        'view'       => true,
        'update'     => true,
        'delete'     => true
    ],
    'description' => 'manage post permissions'
]);

throwing error on passing array within array on create method laravel 5.4 :

Array to string conversion (SQL: insert into permissions (name, slug, description, updated_at, created_at) values (post, 1, manage post permissions, 2017-04-27 05:32:41, 2017-04-27 05:32:41))

Upvotes: 0

Views: 889

Answers (3)

Thamilhan
Thamilhan

Reputation: 13293

Laravel allows Array & JSON Casting mutator:

Just update your Permission model to have:

protected $casts = [
    'slug' => 'array',
];

From the docs:

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

So, now you no need to encode manually, Laravel does everything for you automatically! Just pass array as an array.

Upvotes: 3

Squiggs.
Squiggs.

Reputation: 4474

Slug is a string in the database. You passing an array to it.

You could store it as JSON or Serialise it, but this is a database design smell. You should think about what other tables you need to store this data properly, depending on how it will be used elsewhere in you application.

Upvotes: 0

Mehrud
Mehrud

Reputation: 201

Try json_encode on slug field, then pass it to the Eloquent to persist in DB:

'slug' => json_encode([
   'create' => true,
   'view'   => true,
   'update' => true,
   'delete' => true
)]

Upvotes: 3

Related Questions