Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent split query in multiple steps

I think the title is quite confusing, I will try to explain this as good as possible. Lets say I have quite a big query for searching posts, something like this:

$posts = Post::select('...')
           ->leftJoin('...')
           ->leftJoin('...')
           ->where('...')
           ->orWhere('...')
           ->orderBy('...')
           ->orderBy('...')
           ->groupBy('...')
           ->with('...')
           ->paginate(8);

How can I split this query? For example:

$posts = Post::select('...')
           ->leftJoin('...')
           ->leftJoin('...')

$posts->where('...')
      ->orWhere('...');

$posts->orderBy('...')
      ->orderBy('...')
      ->groupBy('...');

$posts->with('...')
      ->paginate(8);

Im using Laravel 4.2 and I tried several things (including this post), but I can't get it to work. I need this for searching and filtering posts.

like image 698
JasonK Avatar asked Oct 24 '14 17:10

JasonK


1 Answers

Start by creating a new instance of your model and seting it to a variable, build your query using that variable, and then end with a get():

$posts = new Post;
$posts = $posts->where('...');
$posts = $posts->orWhere('...');
$posts = $posts->orderBy('...');
...
$posts = $posts->get();

Rather than doing all this chaining, though, you can probably streamline things quite a bit by using query scopes and some well-structured relation methods.

like image 170
damiani Avatar answered Oct 23 '22 02:10

damiani