Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent
Last updated 2 years ago.
0

Maybe you have the same problem I was having: that Auth::user() is null when called from Scope apply() method. Calling it from the constructor does seem to work.. most of the time. I don't understand why it doesn't always work by either method, but so far, by using the constructor and the apply() as backup, it seems to work all of the time.

<?php namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;

class ShopScope implements Scope
{
    protected $user;

    /**
     * double try to get Auth::user because for unknown reason doesn't always work
     *
     * ShopScope constructor.
     */
    public function __construct()
    {
        $this->user = Auth::user();
    }

    public function apply(Builder $builder, Model $model)
    {
        $user = $this->user ?: Auth::user();

        //your code here
    }

}
Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

slev70 slev70 Joined 28 Jan 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.