06.10.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Database: Query Builder 533<br />

skip / take<br />

To limit the number of results returned from the query, or to skip a given number of results in the<br />

query (OFFSET), you may use the skip and take methods:<br />

1 $users = DB::table('users')->skip(10)->take(5)->get();<br />

Conditional Statements<br />

Sometimes you may want statements to apply to a query only when something else is true. For<br />

instance you may only want to apply a where statement if a given input value is present on the<br />

incoming request. You may accomplish this using the when method:<br />

1 $role = $request->input('role');<br />

2<br />

3 $users = DB::table('users')<br />

4 ->when($role, function ($query) use ($role) {<br />

5 return $query->where('role_id', $role);<br />

6 })<br />

7 ->get();<br />

The when method only executes the given Closure when the first parameter is true. If the first<br />

parameter is false, the Closure will not be executed.<br />

Inserts<br />

The query builder also provides an insert method for inserting records into the database table. The<br />

insert method accepts an array of column names and values to insert:<br />

1 DB::table('users')->insert(<br />

2 ['email' => 'john@example.com', 'votes' => 0]<br />

3 );<br />

You may even insert several records into the table with a single call to insert by passing an array<br />

of arrays. Each array represents a row to be inserted into the table:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!