Back

Change query based on variable from URL


All in the interest of learning Laravel and better coding. This is my controller:

public function index($label = 'false')
{
    $search = Input::get('search');
    if(Input::has('search')) {
        $appointments = Appointment::where('appointment', 'LIKE', '%'. $search .'%')->paginate(25);
    } elseif($label !== 'false') {
        $appointments = Appointment::orderBy($order, $sort)->where('label', '=', $label)->paginate(25);
    } else {
        $appointments = Appointment::paginate(25);
    }
    return view('appointments.index', compact('appointments', 'search', 'label'));
}

In my Appointments view I can click on a label which will route to the appointments.index controller and then execute the correct query. As you can see, when no label has been clicked, and no search has been submitted, the last query ($appointments = Appointment::paginate(25);) will be executed.

I feel that I can write this code better, instead of the if and else statements. Any thoughts? Thanks in advance for any pointers you will be able to give me.

thomastkim replied 3 years ago Solution

Hmm....I can't really see anything except maybe calling paginate(25) at the end instead of repeating it by building upon a single query:

public function index($label = 'false')
{
    $search = Input::get('search');
    $query = Appointment::query();

    if(Input::has('search')) {
        $query->where('appointment', 'LIKE', '%'. $search .'%');
    } elseif($label !== 'false') {
        $query->orderBy($order, $sort)->where('label', '=', $label);
    }
    
    $appointments = $query->paginate(25);
    return view('appointments.index', compact('appointments', 'search', 'label'));
}
RonB1985 replied 3 years ago

Awesome, thanks for your reply once again, I didn't know this either yet :)

Edit: And I see I am using two accounts on here.


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us