Home > Software engineering >  Is there an Laravel Eloquent to SQL converter?
Is there an Laravel Eloquent to SQL converter?

Time:08-24

Is there? Basically a reverse of this useful tool: https://dev.to/jjlabajo/sql-to-eloquent-laravel-converter-tool-1eci

CodePudding user response:

Yes, toSql() method returns the query without running it – good if you don't want to alter data and only get the query – but this method doesn't show the whole query if your query is more complex or if there are sub-queries.

Example:

App\User::query()
    ->where('created_at', '<', now()->subYear())
    ->with('assignedApps', 'courses')
    ->orderBy('email', 'asc')
    ->limit(5)
    ->toSql();

Output:

select * from `users` where `created_at` < ? order by `email` asc limit 5

Using the Laravel Query Log

The second method is the Laravel query log that collects all queries within a request. You can enable this log, run your query and dump the output.

DB::enableQueryLog();

App\User::query()
    ->where('created_at', '<', now()->subYear())
    ->with('assignedApps', 'courses')
    ->orderBy('email', 'asc')
    ->limit(5)
    ->get();

dd(DB::getQueryLog());

output:

array:3 [▼
  0 => array:3 [▼
    "query" => "select * from `users` where `created_at` < ? order by `email` asc limit 5"
    "bindings" => array:1 [▼
      0 => Illuminate\Support\Carbon @1588525477 {#1595 ▶}
    ]
    "time" => 7.97
  ]
  1 => array:3 [▼
    "query" => "select `apps`.*, `user_apps`.`user_id` as `pivot_user_id`, `user_apps`.`app_id` as `pivot_app_id`, `user_apps`.`created_at` as `pivot_created_at`, `user_apps`.` ▶"
    "bindings" => []
    "time" => 2.81
  ]
  2 => array:3 [▼
    "query" => "select `courses`.*, `user_courses`.`user_id` as `pivot_user_id`, `user_courses`.`course_id` as `pivot_course_id`, `user_courses`.`created_at` as `pivot_created_ ▶"
    "bindings" => []
    "time" => 0.54
  ]
]

CodePudding user response:

You can use toSql() method to convert eloquent builder instance to sql query.

  • Related