The issue you're encountering is due to the naming conventions used by Laravel when creating components. When you use the php artisan make:component command with a kebab-case name, Laravel creates the Blade view file with the same kebab-case name, but the PHP class should follow the PSR-4 naming convention, which uses PascalCase (also known as StudlyCase).
Here's how you can resolve this:
-
Rename the Component Class: Change the class name from
nav-linktoNavLinkin yournav-link.phpfile. -
Update the File Name: Rename the file
nav-link.phptoNavLink.phpto match the class name. -
Correct the Namespace and Class Declaration: Ensure the class declaration matches the new class name.
Here's how your component class should look:
<?php
namespace App\View\Components;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class NavLink extends Component
{
/**
* Create a new component instance.
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.nav-link');
}
}
- Blade Component Usage: You can still use the component in your Blade files with the kebab-case syntax:
<x-nav-link />
By following these steps, you ensure that your component class adheres to PHP naming conventions while still allowing you to use the kebab-case syntax in your Blade templates.