0
$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))

7
  • what is error ? Commented Apr 27, 2017 at 5:54
  • What is the error? check your log file and post here. /storage/logs/laravel.log Commented Apr 27, 2017 at 5:55
  • 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)) Commented Apr 27, 2017 at 5:55
  • You'll need to serialize the slug data to store them in a DB cell... Commented Apr 27, 2017 at 5:56
  • create function has array within array, so how come first array is being passed correctly? Commented Apr 27, 2017 at 5:57

3 Answers 3

3

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.

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

1 Comment

Perfect. Thank you.
3

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
)]

2 Comments

yes i know it can work, but my question is why first array is passing correctly.
Laravel out of the box will cast the array into the Eloquent model, but it does not support multi-dimensional arrays, because you are using a RDBMS database, not a NoSql one, unless you use a mutator in your model
0

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.

Comments

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.