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

siusiak1000's avatar

Return projects with the selected category in the view, not in controller

Controller:

$projects = Project::orderBy('data_utworzenia', 'desc')->with('categories')->take(8)->get();

Can I view projects with the selected category in the view?

I know I can do it in the controller:$projects = Project::orderBy('data_utworzenia', 'desc')->with('categories', $category)->take(8)->get();

But I need to substitute a category variable in the view.

0 likes
9 replies
Cronix's avatar

How would you be supplying this category variable in the view? Please explain what you are trying to accomplish functionally. Like, I want to have the user change a select box and have it show the selected category results. Explain it in regular terms, not code.

From your other posts it seems like get an idea on how to solve a problem and start heading down the path you think is correct and ask for help about the path because you run into issues, but the path is wrong to begin with and can be solved a different way. So please take some time and explain what you are wanting to have the app do.

siusiak1000's avatar

I have a project model. With this model I need the name of the category and all the projects that are assigned to it.

$category_with_projects= ProjectCategory::with('projects')->get();
@foreach($category_with_projects as $category)
    {{ $category->name }}

    @foreach($category->projects as $project)
        // ALL CATEGORY PROJECTS
    @endforeach
@endforeach

I would like it to be like this:

-CATEGORY1
    -ALL CATEGORY1 PROJECTS
-CATEGORY2
    -ALL CATEGORY2 PROJECTS
-CATEGORY3
    -ALL CATEGORY3 PROJECTS
siusiak1000's avatar

In such a configuration as above, I get only one project.

Cronix's avatar

You get one project per category? Show the projects relationship definition in the ProjectCategory model. Is it hasMany?

siusiak1000's avatar

I have a pivot table.

    public function projects()
    {
        return $this->belongsToMany('App\Project', 'project_has_categories', 'project_id', 'category_id');
    }

siusiak1000's avatar

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'projects.project_has_categories' in 'where clause' (SQL: select * from projects where projects.project_has_categories in ())

Cronix's avatar

Well, you have to fix what you pass to it too. I was just thinking it's a hasMany relationship. A category hasMany projects?

rin4ik's avatar
 public function projects()
    {
        return $this->belongsToMany('App\Project', 'project_has_categories', 'category_id', 'project_id');
    }

or

 public function projects()
    {
        return $this->hasMany(Project::class);
    }

Please or to participate in this conversation.