I am trying to store a simple form into my database. My model is that I have jobs which where each job can contain several task. Therefore my Models look like this:
User
public function jobs()
{
return $this->hasMany(Job::class);
}
Job
public function user()
{
return $this->belongsTo(User::class);
}
public function tasks()
{
return $this->hasMany(Task::class);
}
Task
public function job()
{
return $this->belongsTo(Job::class);
}
When I now would like to store in the TaskController.php with the following code:
public function store(Request $request, Job $job)
{
$request['job_id'] = $job->id;
$validated = $request->validate([
'message' => 'required|string|max:255',
]);
$request->user()->jobs()->tasks()->create($validated);
return redirect(route('tasks.index'));
}
I get the error:
Call to undefined method IlluminateDatabaseEloquentRelationsHasMany::tasks()
I am pretty sure I am doing a rookie mistake passing the $request but can not figure it out. Thank you for any help!
2
Answers
Calling the relationship function (
$request->user()->jobs()
) will get you the relationship class (IlluminateDatabaseEloquentRelationsHasMany
), not the collection itself. Accessing like$request->user()->jobs
will get you the jobs collection.Your issue is that you are calling
tasks
onjobs
, butjobs()
is a relationship, not a model nor a collection.To fix it, you have to go over each one:
Or, you could try to use a Has Many Through.