Nathaniel
Nathaniel

Reputation: 57

laravel using scope method

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 ?

Upvotes: 2

Views: 11830

Answers (2)

Sandeesh
Sandeesh

Reputation: 11906

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;
}

Upvotes: 3

moathdev
moathdev

Reputation: 256

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 .

Upvotes: 1

Related Questions