5 months ago

WHERE on multiple columns

Posted 5 months ago by RoboRobok

Hi guys,

I need to look for a value in several columns. I was thinking if there is any "cool" way to do it. What I did is:

$columns = ['title', 'description', 'note'];
$needle = 'carrot';

$articles = App\Article::whereIsPublic(true)
    ->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($columns, $needle) {
        foreach ($columns as $column) {
            $query->orWhere($column, $needle);

It creates the query I need just fine:

select *
from `articles`
where `is_public` = 1
and (
  `title` = "carrot"
  or `description` = "carrot"
  or `note` = "carrot"
and `is_finished` = 1
order by `title` asc

Is there any cooler Eloquent way? I don't like the foreach loop here.

Question for educational purposes :)

Please sign in or create an account to participate in this conversation.