Search code examples
laravelmodellaravel-models

Laravel active shipping methods


Table:

       Schema::create('shippings', function (Blueprint $table) {
            $table->id();
            $table->string('name',64);
            $table->integer('price');
            $table->enum('active', ['yes','no'])->default('yes');
            $table->timestamps();
        });
    }

Model:

class Shipping extends Model
{
    const YES = 'yes';
    const NO = 'no';

    public function isActive()
    {
        return $this->active == self::YES;
    }
}

I wanted to show only active ones by using model function like that

 $shipping = Shipping::with('isActive')->get();

But then i get

Error Call to a member function addEagerConstraints() on bool

Am I doing something wrong or is it impossible to make it in this way?


Solution

  • Instead of this you can use laravel scopes Like :

    class Shipping extends Model
    {
        const YES = 'yes';
        const NO = 'no';
    
        public function scopeActive($query)
        {
            return $query->where('active', '=', self::YES);
        }
    }
    

    And then

    $shipping = Shipping::active()->get();