Skip to content

Use views and Blade components in a module

To render views and Blade components from the Blog module, prefix them with the blog namespace. You need an enabled Blog module. A generated module already contains resources/views/index.blade.php and the layout component resources/views/components/layouts/master.blade.php.

  1. Create a view.

    Terminal window
    php artisan module:make-view posts/show Blog

    This creates Modules/Blog/resources/views/posts/show.blade.php (lowercased). Return it from a controller with view('blog::posts.show').

  2. Wrap the view in the module’s layout component (x-blog::layouts.master).

    Modules/Blog/resources/views/posts/show.blade.php
    <x-blog::layouts.master>
    <h1>A post</h1>
    </x-blog::layouts.master>
  3. Create a class-based component.

    Terminal window
    php artisan module:make-component Alert Blog

    This creates two files:

    • Modules/Blog/app/View/Components/Alert.php (Modules\Blog\View\Components\Alert), whose render() returns view('blog::components.alert').
    • Modules/Blog/resources/views/components/alert.blade.php.
  4. Render the component with the blog:: prefix.

    Modules/Blog/resources/views/posts/show.blade.php
    <x-blog::layouts.master>
    <h1>A post</h1>
    <x-blog::alert />
    </x-blog::layouts.master>
  5. Check the result. Add a route to Modules/Blog/routes/web.php and open the page.

    Modules/Blog/routes/web.php
    Route::view('posts/show', 'blog::posts.show')->name('blog.posts.show');
    Terminal window
    php artisan serve

    Open http://127.0.0.1:8000/posts/show. The page displays the heading “A post” and the alert component.

Run module:make-component-view to generate a component view without a PHP class:

Terminal window
php artisan module:make-component-view Card Blog

This creates Modules/Blog/resources/views/components/card.blade.php. Render it as <x-blog::card />.

Use the @module Blade directive in application or module views to render markup only when a module exists and is enabled:

resources/views/layouts/navigation.blade.php
@module('Blog')
<a href="{{ route('blog.posts.index') }}">Blog</a>
@endmodule

Because the package registers @module with Blade::if(), @else and @unlessmodule('Blog') also work.

Override a module view from the application

Section titled “Override a module view from the application”

Publish a module’s views to customize them in the application without editing the module:

Terminal window
php artisan vendor:publish --tag=blog-module-views

This copies Modules/Blog/resources/views to resources/views/modules/blog. Laravel checks the published directory before the module directory. Delete any published files you do not modify so future module updates stay visible.

Edit resources/views/modules/blog/posts/show.blade.php to override blog::posts.show.