Dario Venneri

Organize views by putting Blade Components into subfolders

Oct 5th 2023

The simplest way to use a component is to create a blade file inside the resources/views/components folder.

For example we can create an header.blade.php file, put it into resources/views/components and then include it by writing <x-header /> into any of our views.

But what if we want to organize our components differently? For example we may have all the views of our admin section into a subfolder and then we want to have the components for these section in a subfolder, like this:

views/
├─ admin/
│  ├─ components/
│  │  ├─ header.blade.php
│  ├─ index.blade.php

In this case we need to go to our app/Providers/AppServiceProvider.php and in the boot() method register an anonymous component

use Illuminate\Support\Facades\Blade;

public function boot(): void
{
    Blade::anonymousComponentNamespace('admin.components','admin');
}

Now it's possible to access any component inside the admin/components folder by using <x-admin::name />, so in our example we can access the component with

<x-admin::header />

Create a view class inside a subfolder

Imagine if we have a sidebar component in our admin area listing categories pulled from the database. Do we have to remember to load and pass the categories every time a view uses that component? That's a lot of work, so we can use a view component class. We create one with

php artisan make:component Admin\Sidebar

Now inside app/View/Components/Admin/Sidebar.php we will find our class.

The render() method created by artisan will be like this

public function render(): View|Closure|string
{
    return view('components.admin.sidebar');
}

and we can change it into

public function render(): View|Closure|string
{
    return view('admin.components.sidebar', ['categories' => Category::all()] );
}

we changed the location of the component so that it matches the folder's structure for components we discussed above instead of Laravel's default and then we added the data to pass into the component. And now we create the sidebar.blade.phpview file inside views/admin/components. Then we will be able to include the component with <x-admin.sidebar />.

This way every time the component is included into our views, Laravel will make sure to query the database to retrieve the categories, which we will then be available in $categories inside the sidebar.blade.php component view.

Beware (!!!) that we used <x-admin.sidebar /> instead of <x-admin::sidebar />. If we used the latter we would have loaded the sidebar.blade.php as an anonymous component, and so the $categories variable would not have been created because the component would not have been loaded through the class.