Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Query Builder Default Where Condition

I have News model, when i query news, i want it brings news where status = 1 as default.

News::all(); // select * from news where status = 1
News::where('anotherColumn',2)->get(); // select * from news where status = 1 and where category = 2

Is this possible? What i want is so similar to soft delete feature (it gets where deleted_at is not null and if all data is wanted withTrashed function can be used).

I looked docs but i couldn't find anything helpful. Also, i tried to handle it in construct at News model but it didn't worked either.

Thanks.

like image 356
Bilal Gultekin Avatar asked Jun 30 '14 07:06

Bilal Gultekin


People also ask

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

What is newQuery?

newQuery() is the method that Eloquent use to construct a new query. class News extends Eloquent { public function newQuery($excludeDeleted = true) { return parent::newQuery($excludeDeleted) ->where(status, '=', 1); } } Now your News::all() will only output your news with status = 1. answered Dec 3, 2020 by Niroj.

What is difference between eloquent and query builder?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

How does Laravel query builder work?

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.


1 Answers

I normally override newQuery() for this. newQuery() is the method that Eloquent use to construct a new query.

class News extends Eloquent {

    public function newQuery($excludeDeleted = true) {
        return parent::newQuery($excludeDeleted)
            ->where(status, '=', 1);
    }

}

Now your News::all() will only output your news with status = 1.

like image 88
Unnawut Avatar answered Oct 03 '22 20:10

Unnawut