Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: Extract all entries that begin with a list of provided string

The following request extract all entries from the users table where name=Albert or name=Alberto or name=Ana.

$users = DB::table('users')
    ->whereIn('name', ['Albert', 'Alberto', 'Ana'])
    ->get();

Is there is possibility to adapt this request to extract all entries that begin with the following names ?

like image 770
wawanopoulos Avatar asked Oct 23 '25 17:10

wawanopoulos


2 Answers

Use the like operator on the basic where function:

$users = DB::table('users')
            ->where('name', 'like', 'T%')
            ->get();

Source

Edit: Based on this answer (but simplified), here is a simple closure that solves your question:

$queryStr = ['Albert', 'Alberto', 'Ana'];
$users = DB::Table('users')            
    ->where(function ($query) use ($queryStr) {
         foreach($queryStr as $q){
            $query->orwhere('name', 'like',  $q . '%');
         }      
    })->get();
like image 198
QuickDanger Avatar answered Oct 26 '25 22:10

QuickDanger


Why not chaining orwhere clause:

$names = ['Albert', 'Alberto', 'Ana'];

$users = DB::table('users');

foreach ($names as $name) {
    $users->orWhere('name', 'like', $name.'%');
}

$users = $users->get();
like image 45
YouneL Avatar answered Oct 26 '25 22:10

YouneL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!