Reputation: 798
My table with eloquent relationship in laravel 5.3
User
--id
--name
Gallery
--id
--name
Video
--id
--name
Tags *pivot table
--id
--gallery_id
--video_id
--user_id
--created_at
--deleted_at
Gallery Model:
public function videos()
{
return $this->belongsToMany(Video::class,'tags','gallery_id','video_id')->withPivot('user_id')->withTimestamps();
}
Video Model
public function galleries()
{
return $this->belongsToMany(Gallery::class,'tags','video_id','gallery_id') ->withPivot('user_id')->withTimestamps();
}
My Controller
public function store(Request $request)
{
$data['name]=$request->name;
$video=Video::create($request->name);
$video->galleries()->attach($request->gallery_id,['user_id' => Auth::id()]);
return redirect('/video');
}
and its work is done, But when update face a error (Illegal offset type) Controller Update function
public function update(Request $request, Video $video)
{
$data['name]=$request->name;
$video->update($data);
$video->galleries()->sync([$request->gallery_id=>['user_id'=>Auth::user()->id]]);
return redirect('/video');
}
Anyone Please help me to solve the problem
Upvotes: 2
Views: 1141
Reputation: 1267
$video->update() is looking for an array, where as $request->name is likely a string. Try the following.
public function update(Request $request, Video $video)
{
$video->update(['name' => $request->name]);
$gallery_id = $request->gallery_id;
$video->galleries()->sync([$gallery_id => ['user_id'=>Auth::user()->id]]);
return redirect('/video');
}
You are also mixing up your usage with Auth::id() and Auth::user()->id. Is there a reason for this?
Edit:
Based on the comments, it looks like you were trying to use an array as the index in an array. If you are always dealing with an array, you would have to change your code to look like this, which will build out the array in the proper format.
public function update(Request $request, Video $video)
{
$video->update(['name' => $request->name]);
$sync_array = [];
foreach($request->gallery_id as $gallery_id)
$sync_array[$gallery_id] = ['user_id' => Auth::user()->id];
$video->galleries()->sync($sync_array);
return redirect('/video');
}
If you sometimes have a string, and sometimes have an array, you will have to add a conditional in your code to check for this and make edits to your code accordingly.
Upvotes: 1