Editors Note: The original online tool mentioned below is no longer available and we have replaced the link to point to a cached version.
You can convert raw and legacy SQL queries into a Laravel database query builder version with Orator, an online tool by Maurice Calhoun. This generator could also be an excellent tool for someone learning Laravel, as it can help them translate SQL queries into query builder objects, as learning a new ORM can sometimes be a challenge for new developers.
You simply enter your SQL query, and the generator returns a database query builder. For example, take this SQL query:
1select posts.id, posts.title, posts.body from posts2where posts.author_id = 13order by posts.published_at DESC4limit 10;
The online tool converts it into the following Laravel database query:
1DB::select('posts.id','posts.title','posts.body')2 ->from('posts')3 ->where('posts.author_id', '=', 1)4 ->orderBy('posts.published_at', 'DESC')5 ->limit(10)6 ->get();
Try out this SQL to Laravel Query Builder tool online. One thing to note is that you have to replace “backticks” (`) into strings to get it working because the generated builder gives you backticks when it should give you a string. In PHP, the backticks are execution operators.
For those learning how to work with Laravel’s query builder should check out the query builder documentation. We’ve also recently written about optimizing queries with eager loading and quickly dumping Laravel queries which should help you get up to speed on working with databases in Laravel.