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'));
    }
}
Clinton Green
  • 9,697
  • 21
  • 68
  • 103

2 Answers2

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);
}
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • Ohgodwhy, I got the same error when I call a User model method. How can I solve it? – horse Feb 05 '17 at 19:40
  • @user2356198 Consider asking a new question with a [minimum, complete, verifiable example](http://stackoverflow.com/help/mcve) and you should get a great response. – Ohgodwhy Feb 05 '17 at 20:38
  • @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. – Ohgodwhy Dec 04 '17 at 19:49
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 !

lightWay
  • 31
  • 4
  • 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. – Pavlo Zhukov May 20 '18 at 12:52