简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM