1

I'm new to laravel and i encountered an array to string conversion error while trying to send tags select form data to sync with my blogs table.

Below is blade snippet that retrieves tags from the database

<div class="form-group">
   <label for="tag" class="control-label">Tags</label>
   {!! Form::select('tag[]', $tags, old('tag'), ['class' => 'form-control select2', 'multiple' => 'multiple', 'id' => 'add-tag' ]) !!}   
 </div>

The BlogsController

$blog_data = request()->validate([
            'tag.*' => 'required'
    ]);

 blogs = Blog::create( $blog_data );  
     $blogs->tags()->sync((array)request()->input('tag'));
 

when i perform a dd on request()->tag

  array:2 [▼
  0 => "1"
  1 => "2"
]
1
  • 1
    I think this issue relates to github.com/LaravelCollective/html/issues/464 which I encountered some time ago. The issue is that LaravelCollective/html does not seem to work well with array inputs Commented Jun 27, 2020 at 10:18

2 Answers 2

3

Just use like this

$blogs = Blog::create( $blog_data );  

If insert then use like this

$blogs->tags()->attach($request->tag);

If update then use like this

$blogs->tags()->sync($request->tag);
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the reply. I tried that already and it doesn't work
for the insert operation
@Alkari then you have to use attach
$blogs->tags()->attach( request()->tag); this doesn't work
@Alkari It's a many to many relation right?? If yes then it should be work. I use this code minimum 5 to 7 project at all.
|
1

Thank you, i was able to remove this line of code and it worked

tag.*' => 'required'

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.