8

I am busy with Laravel From Scratch: Updating Records and Eager Loading. I have followed the tut but I am getting this error when trying to add user data in CardsController. I am assuming that I've missed a step in the card user relationship somewhere but I've watched the video 3 times and my database queries for User, Card & Note matches the video exactly.

Is there another step I need to perform after creating the Users table via the migration perhaps?

Error

BadMethodCallException in Builder.php line 2345:

Call to undefined method Illuminate\Database\Query\Builder::user()

CardsController code

<?php
namespace App\Http\Controllers;
use App\Card;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CardsController extends Controller
{
    public function index()
    {
        $cards = Card::all();
        return view('cards.index', compact('cards'));
    }

    public function show(Card $card)
    {
        $card = Card::with('notes.user')->get();
        return $card;
        return view('cards.show', compact('card'));
    }
}

2 Answers 2

11

Your note model is lacking the relationship definition for it's associated user, it looks like.

You should just be able to add the relationship in the Notes model like this:

public function user()
{
    return $this->belongsTo(User::class);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ohgodwhy, I got the same error when I call a User model method. How can I solve it?
@user2356198 Consider asking a new question with a minimum, complete, verifiable example and you should get a great response.
@Solivan You should make a question so we can vet it there, this has been answered and your situation may be a bit more unique.
1

That video does have some problems, so I also encountered the same problem. You should just be able to add the relationship in the Note model like this:

public function user()
{
    //return $this->belongsTo(User::class);
    return $this->belongsTo('App\User');
}

and in the User model like this:

public function notes()
{
    return $this->hasMany(Note::class);
    //return $this->belongsTo('App\Note');
}

bless you !

1 Comment

It looks like you just need to switch belongsTo to hasMany type of relationship in your User model. Changing of string class providing or via PHP has no effect: Note::class equal to 'App\Note' in your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.