In my Laravel application I have two tables: groups and posts. In posts, I have the groups.id
as a foreign key as the posts will belong to a specific group. I am getting the error Attempt to read property "title" on bool
as I am trying to loop through the posts in the blade template file. I know that normally means it failed, but there is data in the posts
table. How can I pull all posts that belong to their respective group?
GroupController.php
namespace AppHttpControllers;
use AppModelsGroup;
use IlluminateHttpRequest;
class GroupController extends Controller
{
/**
* Display the specified resource.
*/
public function show(string $id)
{
$posts = Group::with('posts')->find($id);
return view('groups.single-group', compact('posts'));
}
}
Routes
Route::prefix('group')->middleware('auth')->group(function () {
Route::get('/{id}', [GroupController::class, 'show'])->name('group-page');
});
Models
class Group extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function group()
{
return $this->belongsTo(Group::class);
}
}