Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'));
    }
}
like image 818
Clinton Green Avatar asked Jun 21 '16 00:06

Clinton Green


2 Answers

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);
}
like image 117
Ohgodwhy Avatar answered Nov 06 '22 03:11

Ohgodwhy


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 !

like image 44
lightWay Avatar answered Nov 06 '22 05:11

lightWay