Laravel naming scopes and methods

23-11-2021 · in laravel-developer


In Laravel filters or scopes, better said, can be used when you query a model with a specific method chain. We can start from the following example:
This will take all the posts that are having the published_at column not null, or in simpler words all the posts that are active. With scopes this will look like this:
	class Post extends Model
         * The attributes that should be cast to native types.
         * @var array
        protected $casts = [
            'published_at' => 'datetime',
        public function scopeActive($query)
            return $query->whereNotNull('published_at');
The usage is like this:
The scopes can also accept parameters, as you may need to have a scope that accepts a date and then you can rename the scope like 'scopePublishedUntil' or 'scopePublishedBefore'. This can look like this:
    public function scopePublishedUntil($query, $param)
        return $query->where('published_at', '<=', $param);
You can use it like this:

Has/Is Methods

You can write the methods as you prefer, but keep in mind the basic thing: naming is the key! This is also the most dificult thing to do in programming. I recently encountered a huge bug in some code and that is the naming of so called 'boolean functions' or function that should only return a boolean. The simple rule is that what ever the method name, if it beggins with the words "is" or "has" then the return type must be a boolean. I will give a right example:
    public function isPublished(): bool
        return $this->published_at !== null;
This method will return 'true' or 'false' based on the condition inside. You must watch out for anything else then a boolean for the return type. once again the naming is the key!