Laravel Database Selects And Raw Expressions


Laravel Database Selects And Raw Expressions – The Laravel Database Selects And Raw Expressions both are difference select method is used to select particular column from the database and raw is used to inject expression into the query as string.


Laravel Database Selects And Raw Expressions.

Let us understand how to use Laravel Database Selects And Raw Expressions.

Function:-

There are some followings function available in Laravel Database Selects And Raw Expressions.

  • 1. Selects.
  • 2. Raw Expressions.

1. Selects.

Specifying A Select Clause

Yes you may not always want to select all columns from the database table. By using select method, you can specify a custom select clause for the query.

$users = DB::table('users')->select('name', 'email as user_email')->get();

The distinct method allows you to force the query to return distinct results.

$users = DB::table('users')->distinct()->get();

If you want to add a column to its existing select clause, you may use the addselect
method.

$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();

2. Raw Expressions.

Sometime we have to need use a raw expression in a query. It will be injected expression into the query as a string. To create a raw expression, you can use DB::raw method.

$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

Advertisements

Add Comment

📖 Read More