Laravel Classroom image

pankaj
 
To post your Question Join Classroom
 
Lesson Topics's No:-  |1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9|Last
Lessons:-Fluent Query Builder

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.
1 <?php
2
3 Class::make()->chain()->chain()->chain()->trigger();
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.
1 <?php
2
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
a foreach.
1 <?php
2
3 foreach ($users as $user)
4 {
5 echo $user->email;
6 }
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.

 
 
 

pankaj

Skills    Laravel

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)