1
votes

I am upgrading and refactoring my site to laravel 5.5, and this code is giving me a problem at the moment. I searched in the laravel github docs and didn't find any breaking changes that might affect this.

What I am trying to do is Related To section in my site, In every recipe page I want to display some more recipes that has the same category.

Here is my code:

    public static function getRelatedRecipes($recipe){

      $related_category_ids  = $recipe->category()->pluck('categories.id');

        return $relatedRecipes =
        Recipe::whereHas('categories', function ($q)use($related_category_ids){
        $q->whereIn('category_id', $related_category_ids);
        })
        ->where('id', '<>', $recipe->id)
        ->take(4)
        ->inRandomOrder()
        ->get();
}

This is the recipe model:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Recipe extends Model
{
    protected $guarded=[];

    /**
     * Get the route key name for Laravel.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }



    public function category()
    {
        return $this->belongsToMany('App\Category');
    }

}

What could be the problem?

Thanks,

P.S

If any other code that you think is needed to resolve this, please tell me and I will post it here. :)

1
Recipe is not what you think it is, most likely.Ohgodwhy
@Ohgodwhy the recipe is what i think it is, and when i dd($recipe) i get the full recipe.GabMic
Show us your Recipe model.Marwelln
Many to Many relationships had some breaking changes. Also what's the problem? As in what error you get?DevK
@Eitan I didn't say $recipe isn't what you think it is. I said Recipe isn't what you think it is. What is the fully namespaced path to that class? What are the relationships inside of it/Ohgodwhy

1 Answers

2
votes

First of all make sure, Recipe you use in the method is the model, so instead of

Recipe::whereHas('categories', function ($q)use($related_category_ids){

use

\App\Recipe::whereHas('categories', function ($q)use($related_category_ids){

The other thing is this categories relationship. In model you don't have categories relationship, you have only category relationship