Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shanely's avatar

querybuilder in php artisan tinker

HI, I have querybuilder code written in my IDE editor i want to run this in console in php artisan tinker, I tried to copy and paste in the console but my code messes up.how do you guys run querybuilder code when you use tinker in console ? I cannot format my code

Thank you in advance.

0 likes
7 replies
bobbybouwmann's avatar

You can assign the query to a variable and then continue from there

$query = \DB::table('users')

$query = $query->where('name', 'Me')

$query->get();

3 lines for one query in tinker ;)

I only do small stuff in tinker. If I need to figure out a hard query I create the query first in my sql client (Sequel Pro for Mac) and then write the query out with the querybuilder or Eloquent

skliche's avatar

@shanely I use tinker to test query builder stuff all the time. Just enter the query and have fun, e.g.

$results = App\User::whereBetween( 'updated_at', [\Carbon\Carbon::today()->subWeek(100)->startOfWeek(), \Carbon\Carbon::today()->endOfWeek()] )->get();

works like a charm in tinker.

What do you mean by "code messes up"? Why would you want to format code in tinker? What does your query look like and what kind of problems do you experience?

bobbybouwmann's avatar

@skliche I think the query is really long and has enters in it in his code. Of course you can't do that on a command line ;)

1 like
shanely's avatar

@skliche ,

Did you directly paste that code in the console from your IDE ?, because I tried mine , it gives error it will automatically run the code per line when I paste it so it gets error., I right click in the console to paste my code then it automatically execute it.

for example if this is the query in your IDE how would you paste it to the console

$flights = App\Flight::where('active', 1)
               ->orderBy('name', 'desc')
               ->take(10)
               ->get();
skliche's avatar

@shanely Yes, the fluent interface with line breaks won't work on the command line. You'd have to put a backslash at the end of each but the last line but then it won't work in your IDE.

You can put it on a single line like in my example. That would look like

$flights = App\Flight::where('active', 1)->orderBy('name', 'desc')->take(10)->get();

That works in both the IDE and (copy/paste) on the command line.

Or try this instead:

$q = App\Flight::where('active', 1);
    $q->orderBy('name', 'desc');
    $q->take(10);
$flights = $q->get();

Doesn't look that nice but I like to build the query step by step on the command line until it works as it is supposed to. And when the query works just remove the intermediate object ($q) and the extra semicolons in order to get the fluent interface back if you prefer that.

1 like

Please or to participate in this conversation.