Home > database >  Property [id] does not exist on this collection instance?
Property [id] does not exist on this collection instance?

Time:11-19

I want to show from UserController how many products the User used and user information. I have created two Resources for it. SO I search him using $id Here is My UserController code

public function show($id)
    {
        //
        $user = User::find($id);
        if (is_null($user_id)) {
            return response()->json([
                'message' => 'User Not Found',
                'status' => 404
            ], 404);
        }
        $products = Product::where('user_id', $user->id)->get();
        return response()->json([
            'data' => new UserProductResource($products),
            'status' => 200
        ], 200);
    }

And here is my UserProductResource

<?php

namespace App\Http\Resources;

use App\Http\Resources\ProductResource;
use Illuminate\Http\Resources\Json\JsonResource;

class UserProductResource extends JsonResource
{

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'profile_img' => $this->profile_img,
            'products' => ProductResource::make($this->products),
            
        ];
    }
}

And The error is enter image description here

My Route is:

Route::get('/show-product/{id}', [UserController::class, 'showProduct']);

CodePudding user response:

Try this solution:

You have a error in this query

$products = Product::where('user_id', $user_id)->get();

because $user_id is object of User not a single value.

Your Code:

public function show($id)
{
    //
    $user_id = User::find($id);
    if (is_null($user_id)) {
        return response()->json([
            'message' => 'User Not Found',
            'status' => 404
        ], 404);
    }
    $products = Product::where('user_id', $user_id)->get();
    return response()->json([
        'data' => new UserProductResource($products),
        'status' => 200
    ], 200);
}

New Code:

public function show($id)
{
    //
    $user = User::find($id);
    if (is_null($user)) {
        return response()->json([
            'message' => 'User Not Found',
            'status' => 404
        ], 404);
    }
    $products = Product::where('user_id', $user->user_id)->get();
    return response()->json([
        'data' => new UserProductResource($products),
        'status' => 200
    ], 200);
}

CodePudding user response:

find($id) returns an object so you cant pass object in where(). Replace your below line

$products = Product::where('user_id', $user_id)->get();

with this line

$products = Product::where('user_id', $user_id->id)->get();

it will work.

  • Related