Query Builder
About Query Builder

Laravel's database query builder is use for creating database queries. It works on all supported database systems.

The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

To Fetch full data from Database

Route
Route::get('testuser','Myusercontroller@index');

Controller
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
class Myusercontroller extends Controller
{
public function index()
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}

View
foreach ($users as $user)
{
echo $user->name;
}

To Fetch Single Row from users table where id is 1

Controller Function
$user = DB::table('users')->where('id', '1')->first();
return view('user.index', ['user' => $user]);

View
echo $user->name." ".$user->email;

To Fetch Single column from users table where id is 1

Controller Function
$email = DB::table('users')->where('id', '1')->value('email');
return view('user.index', ['email' => $email]);

View
echo $email;

To retrieve a single row by its id column value, use the find method

Controller Function
$user = DB::table('users')->find(2);
return view('user.index', ['user' => $user]);

View
echo $user->name." ".$user->email;

To Count rows

Controller Function
$countusers = DB::table('users')->count();
return view('user.index', ['countusers' => $countusers]);

View
echo $countusers;

To Find rows where age is maximum

Controller Function
$maxage = DB::table('users')->max('age');
return view('user.index', ['maxage' => $maxage]);

View
echo $maxage;

Combine methods(where and max)

To find maximum age row where city is delhi

Controller Function
$maxage = DB::table('users')
->where('city','delhi')
->max('age');
return view('user.index', ['maxage' => $maxage]);

View
echo $maxage;


Previous
Next