Trying To Get Property 'id' Of Non-object Error (Asset Management System)

- 1 answer

My whole project has been fully functional except for the create feature. When I'm logged on as a regular user, I can view the index of the clothes without any problem. But when logged on as an admin, I can only view the index when I create a new clothe for the first time (which regular user doesn't have access to).

After that first time, the second time I add a new clothe, this error pops up, and I'm trying to figure this out. I'm just starting out with Laravel.

This is the code inside my index function on the controller:

$clothe = Clothe::all();

return view('clothes.index')->with('clothe',$clothe)->with('brand',Brand::all())->with('stock',Stock::all());

The brand pertains to the brand model which is the brands of clothing, while stock is the stock model which pertains to 2 pieces of data, 'Available' and 'Not Available' (take note this works when I'm only logged in as a regular user, but doesn't when I create a second clothe as an admin)

On my clothes index blade, for some reason it reads $brand, $stock and $clothe as non objects.

When the admin creates the second clothing, the data does get stored as I have checked in my database, the only problem is displaying it.

This is my store function:

public function store(Request $request, Clothe $clothe, Stock $stock)
        'name' => 'required|string',
        'price' => 'required|numeric',
        'brand-id' => 'required|numeric',
        'stock-id' => 'required|numeric',
        'description' => 'required|string',
        'image' => 'required|image|max:5000'

    $clothe = new Clothe;

    $clothe->name = $request->input('name');
    $clothe->price = $request->input('price');
    $clothe->brand_id = $request->input('brand-id');
    $clothe->stock_id = $request->input('stock-id');
    $clothe->status_id = 1;
    $clothe->description = $request->input('description');
    $clothe->image = $request->image->store('public');


    return redirect(route('clothes.index'));

and this is my create function

public function create(Clothe $clothe)
    $brand = Brand::all();
    $stock = Stock::all();
    return view('clothes.create')->with('brand',$brand)->with('stock',$stock);


I'm not sure why you are doing this

Line: 34

@foreach($clothe as $clothe)

I dunno if this is what is confusing PHP into sometimes treating '$clothes' as the collection instead of the instance because you are using the same variable name, it should be :

@foreach($clothes as $clothe) 
@foreach($clothe as $singleclothe)


$clothe->stock->id needs to be $clothe->stock()->id dependent on relationship, because you can only call that on eloquent relationships or functions that return a relationship instance else you need to use ().