6

So, here is my controller:

$topics = Topic::where('board_id', $id)->with('user')->get();
$topic = Topic::find($id);
$board = Boards::where('id', $id)->get();
return view('boards.show')->with('topics', $topics)->with('topic', $topic)->with('board', $board);

And here is the code for generating URL's:

@foreach($board as $boards)
<a href="/topics/create/{{$boards->id}}">Create New Post</a>
<p>No Posts Found</p>
@endforeach

But if i'm removing foreach loop, it is giving error:

Property [id] does not exist on this collection instance.

But why do, i have to loop, if it is only getting one row from the boards table?? Any solution of doing it without running for each loop???

Deepak Rawat
  • 131
  • 2
  • 10

2 Answers2

5

Since you want to get just one object, you do not need to use get() to get a collection. Use find() to get an object by it's primary key:

$board = Boards::find($id);

In the view you don't need to use @foreach loop:

<a href="/topics/create/{{ $board->id }}">Create New Post</a>
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
2

You can use Boards::find($id); or Boards::findOrFail($id); insted of Boards::where('id', $id)->get(); for getting a single row.Also use

return view('boards.show')->with('topics', $topics)->with('topic', $topic)->with('board', $board);

to

return view('boards.show',[
   'topics'=> $topics,
   'topic'=> $topic,
   'board'=> $board
 ]);

becouse passing normal values to view using session is not a good practice

Rahul Reghunath
  • 1,210
  • 13
  • 23