M
M
Maxim2019-09-27 14:12:53
Laravel
Maxim, 2019-09-27 14:12:53

Display a list of favorites?

Tell me where I made a mistake, I'm trying to display selected articles, but the error is
Article Model

protected $table = 'articles';
    protected $fillable = [
        'title', 'description', 'image','category', 'source','user_id', 'published','moderation', 'slug','view'
    ];
public function favorite()
    {
        return $this->hasOne(Favorite::class, 'content_id')->where('type', '=', 1);
    }

Model Favorites
protected $table = 'favorites';
    protected $fillable = [
      'content_id', 'type', 'user_id','ip','agent'
    ];

    public function article() //Привязываем к модели статья
    {
        return $this->belongsTo(Article::class, 'content_id')->where('type', '=', 1);
    }

the controller itself
$articles = Favorite::where('user_id', '=', Auth::user()->id)->article()->paginate(15);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav, 2019-09-27
@mzcoding

In your error, it says that the article() method was not found in the Illuminate\Database\Eloquent\Builder class.
And the construction will return an object of the Illuminate\Database\Eloquent\Builder class, and you need an object of your model

D
Dmitry, 2019-10-04
@dlnsk

You have a lot of messed up relationships...
Let's start by defining a one-to-one relationship, which is stupid. At a minimum, you need hasMany.
Well, actually, you have a classic many-to-many relationship (users-articles), where "favorites" is an intermediate table (and, by the way, I don't understand why you need the type field). Lara allows intermediate to make any table. It's well documented in the docs.
Good luck!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question