Line in Linus
Line in Linus

Reputation: 420

Laravel load only Model

I want to load only the model to be able to add wheres etc later.

$query = Users;

if($request->filter == 1) {
   $query = $query->where('user_access', 'admin');
}

if($request->otherFilter == 1) {
   $query = $query->where('user_email', '');
)

$query->get();

Although using $query = Users; doesn't work..?

Upvotes: 1

Views: 84

Answers (3)

Isa Ishangulyyev
Isa Ishangulyyev

Reputation: 91

You should really consider using local query scopes with Eloquent if you are planning to do lots of different queries. Laravel Eloquent Query Scopes

    //App\User.php

    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    $users = App\User::popular()->orderBy('created_at')->get();

You can create custom queries instead of long verbose ones.

Upvotes: 0

Amit Gupta
Amit Gupta

Reputation: 17658

You can use it by creating a Illuminate\Database\Eloquent\Builder instance as:

$query = Users::query();

and then you can add further queries in query builder instance.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You can just create an instanse of the Users model with:

$query = new Users;

And then work with it.

Upvotes: 1

Related Questions