Storm Spirit
Storm Spirit

Reputation: 1510

Why is my model scope not working and returning an empty array?

Why do I get an empty collection result using the scope? This is my current controller:

class PunxController extends Controller {
    public function index()
    {
        $scholars = Scholar::age()->get();

        return $scholars;
    }
}

and on my model Scholar:

use Illuminate\Database\Eloquent\Model;

class Scholar extends Model {

    protected $primaryKey = 'scholar_id';
    protected $fillable = ['ngo_id','scholar_lname','scholar_fname','scholar_image','scholar_nickname','scholar_cityAddress','scholar_permaAddress','scholar_birthday','scholar_placebirth','scholar_age','scholar_gender','scholar_email','scholar_contact'];

    public static function scopeAge($query)
    {
        return $query->where('scholar_age', '>=', 5);
    }
}

and the result is:

enter image description here

but when I try on PHPMYADMIN:

enter image description here

Update1

result of DB::getQueryLog():

enter image description here

Upvotes: 0

Views: 1817

Answers (2)

5a494d
5a494d

Reputation: 1

Try this:

public function scopeAge($query)
{
    return $query->where('scholar_age', '>=', 5);
}

Upvotes: 0

Jonathon
Jonathon

Reputation: 16333

Remove the static keyword from your method. Scopes shouldn't be static.

public function scopeAge($query)
{
    return $query->where('scholar_age', '>=', 5);
}

I'm guessing you would like to provide 5 as a parameter to the scope rather than hard-coding it. In which case you can do:

public function scopeAge($query, $age)
{
    return $query->where('scholar_age', '>=', $age);
}

And call it like

Scholar::age(5)->get();

Upvotes: 2

Related Questions