incense_stick
incense_stick

Reputation: 478

Error : Trying to get property of non-object

I have table Authors and table Uploads and I am simply trying to get all uploads for a certain author by author_id in the Uploads table.

For that purpose I have a method in my controller looking like this :

public function author_works()
    {

        $uploads= Upload::where('author_id', 3)->first();

        return view('author-works')->with('uploads',$uploads);
    }

My view is :

  @extends('layouts.app')
@section('content')
    <h1>Uploads</h1>
    @if(count($uploads)>0)
        @foreach($uploads as $upload)
            <div class="well">
                <h3><a href="/uploads/{{$upload->id}}">{{$upload->name}}</a> </h3>
                <small>Written on {{$upload->created_at}}</small>

            </div>
        @endforeach
      {{--  {{$uploads->links()}}--}}
    @else
        <p>No uploads found</p>
    @endif

@endsection

When I debug with dd($uploads); in the controller I am seeing the following, which is actually the right record :

 #attributes: array:9 [▼
    "id" => 7
    "name" => "Fsdf"
    "description" => "fsdfsdffds"
    "created_at" => "2017-12-07 21:29:53"
    "updated_at" => "2017-12-07 21:29:53"
    "user_id" => 1
    "avtor_id" => 3
  ]
  #original: array:9 [▼
    "id" => 7
    "name" => "Fsdf"
    "description" => "fsdfsdffds"
    "created_at" => "2017-12-07 21:29:53"
    "updated_at" => "2017-12-07 21:29:53"
    "user_id" => 1
    "avtor_id" => 3
  ]

Can someone explain why am I getting the error?

Upvotes: 1

Views: 34

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

When you're using first() method, you're getting an object instead of collection. Use get():

$uploads = Upload::where('author_id', 3)->get();

Upvotes: 2

Related Questions