Level 2
I solved the problem:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3|max:15',
'itag' => 'required'
]);
$interest = new Interest();
$interest->name = $request->name;
$interest->save();
if($interest)
{
$itagNames = explode(',' ,$request->get('itag'));
$itagIds = [];
foreach($itagNames as $itagName)
{
//$interest->itags()->create(['itag'=>$tagName]);
//Or to take care of avoiding duplication of Tag
//you could substitute the above line as
$itag = Itag::firstOrCreate(['itag'=>$itagName]);
if($itag)
{
$itagIds[] = $itag->id;
}
}
$interest->itags()->sync($itagIds);
}
$user = Auth::user();
$interest->user()->sync($user);
return back()->with('success', lang::get('messages.newinterest'));
1 like