Support the ongoing development of Laravel.io →
Database Eloquent Views

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.

Last updated 3 years ago.
0

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'));
}
0

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.

Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Hardist hardist Joined 26 May 2015

Moderators

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

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.