Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eggplantSword's avatar

Add relationship to eloquent query to model with scopes

I have this code in my model, but then using eloquent if I add a with('parent') the query stops working. Important side note this is not my code.

    public function parent()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

    function scopeName($query, $request)
    {
        if ($request['query'] && $request["query"]["generalSearch"] != '') {
            $query->orwhere('name', 'like', '%' . $request["query"]["generalSearch"] . '%');
        }
    }

    function scopeOrder($query, $request)
    {
        if ($request['sort'] && $request["sort"]["field"] != '' && $request["sort"]["sort"] != '') {
            $query->orderBy($request["sort"]["field"], $request["sort"]["sort"]);
        }
    }

This is the query that works so far.

function getCategories(Request $request)
    {
            $pagination = $request->query('pagination');
            $categories = Category::Name($request)
                ->Order($request)
                ->paginate($request['pagination']['perpage'], ['*'], 'page', $pagination['page']);
    }

Why can't I add a relationship to this query and how do I fix it?

0 likes
2 replies
eggplantSword's avatar

If I add it here it does work, I had been adding it first before Name

 $categories = Category::Name($request)
                ->Order($request)
				->with('parent')
                ->paginate($request['pagination']['perpage'], ['*'], 'page', $pagination['page']);

Why does it work in that spot and not first?

orest's avatar

Your question is why your code does not work when you call with('parent') but you are not calling that anywhere in your initial post

Please or to participate in this conversation.