Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a query in Laravel with Eloquent?

I'm trying to write the following code:

foreach($relations as $relation){
    $query->orWhereHas($relation, function ($query) use ($filter) {
        $query->where('name', 'like', '%'.$filter.'%');
    });
}

but I don't know how to initialize the $query variable, I'd prefer not to write the first orWhereHas before the foreach starts. Anyone knows how to achieve this? Thanks!

like image 482
Sofia Gilardino Avatar asked Oct 26 '16 21:10

Sofia Gilardino


People also ask

How do you do an eloquent query?

The first method to get the query of an Eloquent call is by using the toSql() method. This method returns the query without running it – good if you don't want to alter data and only get the query – but this method doesn't show the whole query if your query is more complex or if there are sub-queries.

What is eloquent query in Laravel?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

What is query () in Laravel?

In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates, etc. and it works on all supported database systems like a champ.


1 Answers

Eloquent models has query() method. Then, you can do this

$query = App\User::query();
like image 140
pablorsk Avatar answered Sep 30 '22 06:09

pablorsk