2

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 ?

5
  • 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. Commented May 29, 2017 at 10:16
  • It does but I'm still getting the same error Commented May 29, 2017 at 10:18
  • How about Support::where('id', $id)->user()->owner(Auth::user()->id)->first(); ? Commented May 29, 2017 at 10:22
  • now im getting this BadMethodCallException in Builder.php line 2451: Call to undefined method Illuminate\Database\Query\Builder::user() Commented May 29, 2017 at 10:22
  • Could you show how you defined relation between Support and User? Commented May 29, 2017 at 10:23

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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 .

1 Comment

Well it's working now but, should i be defining scopes in the same model im calling them from ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.