Create tags in laravel post publishing



PHP Snippet 1:

//get old vaghts title
$existingVaghts = $food->vaghts->pluck('title')->toArray();

//find new vaghts
foreach($request->vaghts as $vaght) {
    if(! ( in_array($vaght, $existingVaghts) ) ) {
        //create a new vaght
        $newVaght = new App\Vaght;
        $newVaght->title = $vaght;
        $newVaght->save();
    }
}

$attachableVaghts = [];

foreach($request->vaghts as $vaght) {
    $attachableVaghts[] = App\Vaght::where('title', $vaght)->pluck('id')->first();
}

$food->vaghts()->sync($attachableVaghts);

PHP Snippet 2:

$attachableTags = [];
foreach ($request->tags as $tag) {
    $attachableTags[] = Tag::firstOrCreate([
        'name' => $tag
    ])->id;
}
$post->tags()->sync($attachableTags);