I am just trying to wrap my head around this. You want to show one table in total with a random mix of users and posts? Is that correctly understood?
Dec 27, 2021
19
Level 7
Pagination to 2 seperate variables
Hello, I'm trying to make a search in my website which works on posts/users, so i want if a user searched for something the code will search for it 2 models like here
//That's inside the Post Model
public function scopeFilter($query, $search)
{
$query->when($search ?? false, function ($query, $search) {
$query->where(function ($query) use ($search) {
$query->where('title', 'like', '%' . $search . '%')
->orWhere('body', 'like', '%' . $search . '%')
->orWhere('excerpt', 'like', '%' . $search . '%');
});
});
}
//And that's inside the User model
public function scopeFilter($query, $search)
{
$query->where('username', 'like', '%' . $search . '%')->orWhere('name', 'like', '%' . $search . '%');
}
//and in the controller im returning data as follow
if(request('search')) {
$users = User::Filter(request('search'))->paginate(6)->withQueryString();
$posts = Post::Filter(request('search'))->paginate(6)->withQueryString();
return view('posts.search-index', [
'posts' => $posts,
'users'=>$users,
]);
}
now in the blade file i have to make 2 tables for each model's data(Post,User) to show search results, but what i really want is to show both results in 1 table using 1 paginate for all the data gathered
Level 102
@NeVeDlE Yeah you of course need to make them select the same columns. That is the problem with mixing two different kinds of data. Here is an example.
$usersQuery = User::filter(request('search'))->select('id', 'name');
$fullQuery = Post::filter(request('search'))->select('id', 'name')->union($usersQuery);
$results = \DB::query()
->fromSub($fullQuery, "all_items")
->paginate(6);
1 like
Please or to participate in this conversation.