How To Group The Parameters Using Where Clause In Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

Sometimes you may need to create more advanced where clauses such as "where exists" clauses or nested parameter groupings. The Laravel query builder can handle these as well

How to Group The Parameters Using Where Clause In Laravel

In Sql we can group the parameter like below query

select * from employee where name = 'shiva' and (age > 25 or gender = 'male')

 

To learn more about SQL, please visit our BajarangiSoft site.

Parameter Grouping in Laravel
To get started, let's look at an example of grouping constraints within parenthesis:


Example(1)
app/Http/Controllers/studentController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;

class studentController extends Controller
{
    function index()
    {

        $student = DB::table('employee')
            ->where('name', '=', 'shiva')
            ->where(function ($query) {
                $query->where('age', '>', 25)
                    ->orWhere('gender', '=', 'male');
            })
            ->get();
        return view('student.index', ['student' => $student]);
    }
}
?>


In above example group the three parameter name , age, gender from student table and fetching that data to index.blade.php
 

resources/views/student/index.blade.php

<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> Group The Parameters Using Where Clause In Laravel</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <br />
    <h3 align="center">Group The Parameters Using Where Clause In Laravel</h3>
    <br />
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>name</th>
                <th>id</th>
                <th>address</th>
                <th>gender</th>
                <th>age</th>
            </tr>
            </thead>
            <tbody>
            @foreach($student as $row)
            <tr>
                <td>{{ $row->name }}</td>
                <td>{{ $row->id }}</td>
                <td>{{ $row->address }}</td>
                <td>{{ $row->gender }}</td>
                <td>{{ $row->age }}</td>
            </tr>
            @endforeach
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

routes/web.php
Route::get('student', 'studentController@index');

Related Post