So following on the excellent Laravel 5 Fundamentals series here at Laracasts. I have been inspired to add tags to my many jobs which I post up on my website. However, I let the user define what tags they would like rather than me prescribe a set list, so I quite neatly use Eloquent's firstorcreate method.
My issue is that when I want to link my jobs up to my tags in the 'job_tag' pivot table, I cannot seem to multiply insert rows into the pivot table. For example a user might add a description a job and then add multiple tags. Eloquent nicely creates the jobs and the tags which need creating but only inserts one row into the pivot table.
My code is below and would super value people's views on how this may work. I have not found any answer to this in any documentation or on stack overflow so would be nice to have a documented solved answer for the community to see.
My controller:
public function store(CreateJobRequest $request, JobContract $repository)
{
try
{
$repository->createJob($request->except('tags'));
$repository->createTags($request->input('tags'));
$repository->save();
}
catch (FailedJobCreateException $e)
{
return Redirect::back()
->withErrors($e->getErrors())
->withInput($request->all());
}
Flash::overlay(Lang::get('rocketcandy.success-job-create'));
return Redirect::route('home');
}
My EloquentJobRepository:
function createJob(array $data)
{
$data['user_id'] = Auth::id();
if (! $job = $this->job->fill($data))
throw new FailedJobCreateException;
// Probably need to queue this
return true;
}
function createTags($data)
{
$tags = $this->splitTags($this->cleanTags($data));
for ($i = 0; $i < count($tags); $i ++)
{
if (! $tag = $this->tag->firstOrCreate(array('name' => $tags[$i])))
throw new FailedJobCreateException;
$this->tagIds[] = $tag->id;
}
return true;
}
public function save()
{
$this->job->save();
foreach ($this->tagIds as $tagId)
{
if (! $this->job->tags()->attach($tagId))
throw new FailedJobCreateException;
}
return true;
}
Tags are added in the following manner 'tag1, tag2, tag3' and are then trimmed and exploded in PHP.