Skip to content

Query Scopes in laravel

Reading Time: < 1 minute

Applying conditions to queries gives you to power to retrieve and present filtered data in every imaginable manner. Some of these conditions will be used more than others, and Laravel provides a solution for cleanly packaging these conditions into easily readable and reusable statements, known as a scope. In this tutorial I’ll show you how to easily integrate scopes into your Laravel models.

Consider a filter that only retrieves completed list tasks. You could use the following where condition to retrieve those tasks:

$completedTasks = Task::where('done', true)->get();

You might however wish to use a query such as this at multiple locations throughout an application. If so, you can DRY the code up a bit by instead using a scope. A scope is just a convenience method you can add to your model which encapsulates the syntax used to execute a query such as the above. Scopes are defined by prefixing the name of a method with scope, as demonstrated here:

class Task extends Model
{

    public function scopeDone($query)
    {
        return $query->where('done', 1);
    }

}

With the scope defined, you can execute it like so:

$completedTasks = Task::done()->get();

Here we can re-use query logic to encapsulate the database logic inside the model class methods.

For example if you have model called posts.php and if u have 3 types of post status fields called published,private,draft.

To get all the published posts :

class Posts extends \Eloquent {
public function getPublishedPosts()
{
return Posts::where(['status' => 'published'])->get();
}

}

Example:

class Posts extends \Eloquent {

public function scopePublished($query)
{
return $query->where(['status => 'published']);
}
public function getPosts()
{
return $this->published()->get();
}

}

How to pass parameters to scope:

class Posts extends \Eloquent {

public function scopePublished($query,$isActive)
{
return $query->where(['status => 'published','is_active' => $isActive]);
}
public function getPosts()
{
return $this->published(1)->get();
}

}
See also  HTML5 - New Features
Tags:

Leave a Reply