1
votes

I'm trying to learn laravel scoping, I created my first scope but im getting this error message npw

ErrorException in Support.php line 26: Undefined property: Illuminate\Database\Eloquent\Builder::$User

And this is the line

public static function getTicket($id)
{
    $ticket = Support::where('id', $id)->User::owner(Auth::user()->id)->first();
    return $ticket;
}

and this is in user model

public function scopeOwner($query, $flag)
{
    return $query->where('user_id', $flag);
}

Relation between user and support

public function user()
{
    return $this->belongsTo('App\User');
}

Can you please explain to me what am i doing wrong ?

2
My first guess would be: Support::where('id', $id)->user->owner(Auth::user()->id)->first(); But Support model must have relation with User model for this.arbogastes
It does but I'm still getting the same errorNathaniel
How about Support::where('id', $id)->user()->owner(Auth::user()->id)->first(); ?arbogastes
now im getting this BadMethodCallException in Builder.php line 2451: Call to undefined method Illuminate\Database\Query\Builder::user()Nathaniel
Could you show how you defined relation between Support and User?arbogastes

2 Answers

2
votes

You're using the scope wrong. The scope should be in the model on which you wish to use it. So move it to Support model.

public function scopeOwner($query, $id)
{
    return $query->where('user_id', $id);
}

public static function getTicket($id)
{
    $ticket = Support::where('id', $id)->owner(Auth::user()->id)->first();

    return $ticket;
}

You can also do this

public static function getTicket($id)
{
    $ticket = static::where('id', $id)->owner(auth()->id())->first();

    return $ticket;
}
1
votes

remove "User::" like this :

public static function getTicket($id)
{
    $ticket = Support::where('id', $id)->owner(Auth::user()->id)->first();
    return $ticket;
}

then move function scopeOwner from user model to Support model .