0

I have problem with this error. I made relationship between :

  • Meals-Category (hasOne)
  • Meals-Ingredients (hasMany)
  • Meals-Tags (hasMany)

Everything is normal with seeding, but when I want to open on endpoint, this messege shows :

"Attempt to read property "id" on null"

Here is my code from Meals Resources, Model and Controller :

Resource:

class Meals extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'description' => $this->description,
            'status' => $this->deleted_at > 0 ? 'deleted' : 'created',
            'category' => [
                'id' => $this->category->id,
                'title' => $this->category->title,
                'slug' => $this->category->slug,
            ],
            'tags' => TagsResource::collection($this->tags),
            'ingredients' => IngredientsResource::collection($this->ingredients),
        ];
    }
}

Model:

class Meals extends Model
{
    use SoftDeletes;
    use HasFactory;

    protected $fillable = ['title', 'description'];

    protected $dates = ['deleted_at'];

    public function category()
    {
        return $this->hasOne(Category::class, 'meals_id');
    }

    public function tags()
    {
        return $this->hasMany(Tag::class, 'meals_id', 'id');
    }

    public function ingredients()
    {
        return $this->hasMany(Ingredient::class, 'meals_id', 'id');
    }
}

Controller:

public function index()
{
    $meals = Meals::with('category', 'tags', 'ingredients')->get();

    return MealsResource::collection($meals);
}
lagbox
  • 48,571
  • 8
  • 72
  • 83
Zlatnii
  • 11
  • 1
  • 2
    welcome to stack-overflow! :) please provide your code in the question instead of a photo of the code. – newbie Jan 30 '22 at 10:32
  • Does this answer your question? [Notice: Trying to get property of non-object error](https://stackoverflow.com/questions/22636826/notice-trying-to-get-property-of-non-object-error) – ManojKiran A Jan 30 '22 at 10:35

1 Answers1

0

your error means that $this->category is null

assign the category attribute like this :

'category' => $this->load('category')
viryl15
  • 454
  • 4
  • 9