Why quote to get data after using WHERE in Laravel?

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 the urls:

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

But if I delete the foreach loop, it gives an error:

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

But why, should I go in cycles if it only receives one line from the table of payments? Any solution to do this without starting for each cycle ???

+5
source share
2 answers

Since you want to get only one object, you do not need to use get() to get the collection . Use find() to get the object using the primary key:

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

In the view, you do not need to use the @foreach :

 <a href="/topics/create/{{ $board->id }}">Create New Post</a> 
+4
source

You can use Boards::find($id); or Boards::findOrFail($id); insted from Boards::where('id', $id)->get(); to get one line. 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 ]); 

since passing normal values ​​for viewing using a session is not good practice

+2
source

Source: https://habr.com/ru/post/1274357/


All Articles