Fluent Query Builder
Fluent is another wonderful library that Laravel provides to help me dodge the SQL bullet,
although you can still write raw SQL statements if you happen to enjoy pain. The best part
about using Fluent, apart from the lack of SQL, is that it uses prepared statements which are
fully protected against SQL injection. Fluent is also… well fluent in a number of different SQL
dialects, so your methods will work across a variety of databases. Before we get started you will
need to understand the concept of method chaining, take a look at this example.
This is a very useful way of stringing options together, and is a lovely way of expressing SQL
(as you will see later). The class is instantiated with the make() method. Sometimes you will
also pass ‘startup parameters’ to the class this way. The chain() methods are used to modify the
request with different options, and the trigger() method is used to bring back the final result.
This might sound a bit confusing, but let’s take a look at an example from fluent.
3 $users = DB::table('users')->where('username', '=', 'dayle')->get();
The above example will execute a simple..
1 SELECT * FROM users WHERE username = 'dayle';
and bring back an array of objects, representing database rows that are the result of the query.
The table() method is instantiating the object, and setting the table that we intend to work
with. The where() is a chain method that applies a WHERE clause to our query, and get() is the
final trigger method that retrieves all objects that are the result of the query.
The get() trigger will bring back an array of results, so lets start by looping the result set with
3 foreach ($users as $user)
5 echo $user->email;
As you can see in the above example, fields for the row are accessed using the attributes of the
result object. The loop above would output the email addresses for all of our users.