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???

2 Answers 2

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>
1
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

1
  • and also change href="{{ route('routeName',['id' => $user->id]))}}" , which is the best practice in laravel Dec 27, 2017 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.