Laravel Eloquent Query Builder Default Where Condition

I have a news model when I request news, I want it to bring news when status = 1 by 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 it possible? What I want is so similar to the soft delete function (it gets where deleted_at is not null, and if all the data is required using the Traphed function, you can use it).

I looked at the documents, but I could not find anything useful. In addition, I tried to process it in the constructor in the news model, but it did not work either.

Thanks.

+6
source share
2 answers

I usually override newQuery() for this. newQuery() is the method that Eloquent uses to create 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 display your news with status = 1.

+14
source

I think the closure you get without actually changing some core files ...

- Request area ...

Areas of application make it easy to use query logic in your models. To define a scope, simply prefix a model method with a scope:

 class News extends Eloquent { public function scopeStatus($query) { return $query->where('status', '=', 1); } } 

Use of this area

  $news = News::status()->get(); $news2 = News::status()->where('anotherColumn',2)->get(); 

This is not exactly what you wanted ... but its definitely a bit shorter than typing

  News::where('status','=',1)->get(); 

again and again

+5
source

Source: https://habr.com/ru/post/971523/


All Articles