I have two tables at db, one of them is named users
which simply contains user information of website and the other one is tags
which contains some hashtags that users can choose from them.
(just like Stackoverflow that a user can select multiple tags such as php, javascript & etc)
So in order to make this relationship between these two, I added this to User
model:
public function tags()
{
return $this->belongsToMany(Tag::class);
}
And also this one to Tag
model:
public function users()
{
return $this->belongsToMany(User::class);
}
And here is the select option on blade, and users can select multiple tags from db:
<select class="form-control BSinaBold" name="skills[]" id="skills" multiple>
@foreach(\App\Models\Tag::all() as $tag)
<option value="{{ $tag->id }}" {{ in_array($tag->id , Auth::user()->tags->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $tag->name }}</option>
@endforeach
</select>
Then at the Controller, I added this in order to update data at tags
table:
public function update(Request $request, $profile)
{
$validate_data = Validator::make($request->all(),[
'job' => 'nullable',
'stackoverflow' => 'nullable',
'github' => 'nullable',
'instagram' => 'nullable',
'linkedin' => 'nullable',
'website' => 'nullable',
'location' => 'nullable',
'skills' => 'array',
]);
$user = User::findOrFail($profile);
$user->update([
'job' => request('job'),
'stackoverflow' => request('stackoverflow'),
'github' => request('github'),
'instagram' => request('instagram'),
'linkedin' => request('linkedin'),
'website' => request('website'),
'location' => request('location'),
]);
$user->tags()->sync(request('skills'));
$user->save();
return view('profile');
}
And it works fine and perfect but the only problem is this line, that does not sync data at tags
table:
$user->tags()->sync(request('skills'));
So I tried debugging and I found out that request('skills')
is EMPTY!
So the question is, why it does not send any data to the Controller?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.
I think you define your model relation wrong. Tag model should be:
public function user()
{
return $this->belongsTo(User::class);
}
and the User Model relations:
public function tags()
{
return $this->hasMany(Tag::class);
}
If you aim to establish a one-to-many relation.