Search code examples
phplaravellaravel-5.3

Laravel Error leftJoin : Undefined property: Illuminate\Database\Eloquent\Collection::$id


i'm using the leftJoin on laravel, but it get an error

Undefined property: Illuminate\Database\Eloquent\Collection::$id

here the sample code on Controller

$news = News::find($id)
            ->leftJoin('categories', 'news.category_id', '=', 'categories.id')
            ->get();

    //dd($news);

    return view('news.update')
    ->with('news', $news);

I've been trying using get()->first() but it just show the first record only. And if i using foreach on blade like this, the error is just the same

<form class="form-horizontal" action="/news/{{$news->id}}" method="post" enctype="mulipart/form-data">
<select name="category_id">
    <option> - </option>
    @foreach($news as $news)
    <option value="{{ $news->category_id }}" selected>{{ $news->category }}</option>
    @endforeach 
</select> </form>

Solution

  • Try to do like this

    $news = DB::table('news')
              ->leftJoin('categories', 'categories.id', '=', 'news.category_id')
              ->select('news.*', 'categories.*')
              ->get();
    

    ->select('news.', 'categories.') // To select all records from news and category

    <form class="form-horizontal" action="/news/{{$news[0]->id}}" method="post" enctype="mulipart/form-data">
      <select name="category_id">
          <option> - </option>
          @foreach($news as $news_data)
            <option value="{{ $news_data->category_id }}" selected>{{ $news_data->category }}</option>
          @endforeach 
      </select> 
    </form>