简体   繁体   中英

Laravel Call to undefined method in eloquent model

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!

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM