Home > Back-end >  Eloquent first with a custom defined preference order
Eloquent first with a custom defined preference order

Time:02-24

Is there a shorter & elegant way to instruct the first method in eloquent to pick up the matching records using a custom preference order?

Example: ( pick up config A then B then Default )

$config = Configs::whereIn('section', ['A','B', 'default'])
    ->first() // Picks A or B or default;

To eliminate having to write a code like the following

    $config = Configs::where('section', 'A');

    if(!$config)
        config = Configs::where('section', 'B');
    elseif(!$config)
        config = Configs::where('section', 'default');

CodePudding user response:

You can simply provide some ordering based on section and ->first() will select the "correct" record:

$config = Configs::whereIn('section', ['A', 'B', 'default'])
->orderBy('section')
->first();

If section: A is present, then $config will be A, will an implicit fallback to section: B or section: default based on ordering.

Edit: Config:: -> Configs::, but remember, Laravel Model names are Singular by convention.

  • Related