DEV Community

Cover image for Laravel 11 Custom Component File Structure
Arman Rahman
Arman Rahman

Posted on

1

Laravel 11 Custom Component File Structure

Would you like to create a component like this, or do you prefer to develop your own custom component in Laravel with a custom path?

Image description

Then you need to follow few steps

Step 1: Create a Service Provider

php artisan make:provider PackageServiceProvider
Enter fullscreen mode Exit fullscreen mode

You can name it your own.

Step 2: Add Blade::componentNamespace('App\View\Backend\Components', 'backend'); on your boot() method

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class PackageServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        Blade::componentNamespace('App\View\Backend\Components', 'backend');
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Create a php file as per your file structure. I created my file here.

app\View\Backend\Components\AdminSidebar.php

Step 4: Return your blade directive on render() method.

<?php

namespace App\View\Backend\Components;

use Illuminate\View\Component;
use Illuminate\View\View;

class AdminSidebar extends Component
{
    /**
     * Get the view / contents that represents the component.
     */
    public function render(): View
    {
        return view('backend.components.sidebar');
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 5: Create your blade file as you mentioned. For my case I added like this.

resources\views\backend\components\sidebar.blade.php

Step 6: Your Component setup is done. now you can access that component by this-

<x-backend::admin-sidebar />
Enter fullscreen mode Exit fullscreen mode

Hope this will help you. Thank You.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs