LearnProgramming
LearnProgramming

Reputation: 806

Is it possible to append laravel DB queries?

CODES IN CONTROLLER

public function getAthleteProperties(Request $request)
{
    $getAthlete = DB::table('students')
                ->join('sports', 'students.id', '=', 'sports.athlete');
                ->select('students.*', 'sports.*')
                ->get();

    if($request->input('gender') == 1)
    {
        //add this line of queries to $getAthlete queries
        ->where('gender', "m");
    }
    else
        ->where('gender', "f");

    if($request->input('active') == 1)
    {
        //add this line of queries to $getAthlete queries
        ->where('active', "y");
    }
    else
        ->where('active', "n");

    return view('admin', compact('getAthlete'));
}

Is it possible to append queries in laravel? For example I have codes as shown on above codes, if the condition for gender is 1 and active is 1 then in the end of the $getAthlete queries will become like this. Is it possible? How?

    $getAthlete = DB::table('students')
                ->join('sports', 'students.id', '=', 'sports.athlete');
                ->select('students.*', 'sports.*')
                ->where('gender', "m") //added because condition is true
                ->where('active', "y") //added because condition is true
                ->get();

Upvotes: 4

Views: 3390

Answers (1)

Ramy Herrira
Ramy Herrira

Reputation: 624

You don't have to use the "get" method at first, since it executes the select statement.

public function getAthleteProperties(Request $request)
{
    $getAthlete = DB::table('students')
                ->join('sports', 'students.id', '=', 'sports.athlete')
                ->select('students.*', 'sports.*');

    if($request->input('gender') == 1) {
        //add this line of queries to $getAthlete queries
        $getAthlete->where('gender', 'm');
    } else {
        $getAthlete->where('gender', 'f');
    }

    if($request->input('active') == 1) {
        //add this line of queries to $getAthlete queries
        $getAthlete->where('active', 'y');
    } else {
        $getAthlete->where('active', 'n');
    }
    $getAthlete = $getAthlete->get();

    return view('admin', compact('getAthlete'));
}

UPDATE:

With the latest versions of laravel a conditional clause method was introduced. So we can do it this way:

$getAthlete = DB::table('students')
    ->join('sports', 'students.id', '=', 'sports.athlete')
    ->select('students.*', 'sports.*')
    ->when($request->input('gender') == 1, function ($query) {
        return $query->where('gender', 'm');
    }, function ($query) {
        return $query->where('gender', 'f');
    })
    ->when($request->input('active') == 1, function ($query) {
        return $query->where('active', 'y');
    }, function ($query) {
        return $query->where('active', 'n');
    })
    ->get();

Upvotes: 7

Related Questions