Home > Enterprise >  Laravel Call to undefined method in eloquent model
Laravel Call to undefined method in eloquent model

Time:01-06

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 Illuminate\Database\Eloquent\Relations\HasMany::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!

CodePudding user response:

Your issue is that you are calling tasks on jobs, but jobs() is a relationship, not a model nor a collection.

To fix it, you have to go over each one:

$request->user()
    ->jobs()
    ->each(function (Job $job) use ($validated) {
        $job->tasks()
            ->create($validated);
    });

Or, you could try to use a Has Many Through.

CodePudding user response:

Calling the relationship function ($request->user()->jobs()) will get you the relationship class (Illuminate\Database\Eloquent\Relations\HasMany), not the collection itself. Accessing like $request->user()->jobs will get you the jobs collection.

  • Related