How to Create Component in Laravel

Introduction Laravel Component -: we know that the laravel is a php framework. When we install laravel project all the package are install automatically. Component are piece of code that is use in multiple file. for example if we are creating a header file then we give the same design in the many page’s in this condition we use the component for creating a header file.

component in laravel

How to create a Component –: Component are automatically install when we install any project in laravel. We can create component manually also. First open the project using the cmd command. Now give the command.
php artisan make:component component_name

Suppose we are creating a component that name is header. Its generate two type file.

1-: First is the HTML file that will available in resources and view folder. File name is the header.blade.php this file is the HTML file.

2-: Another file is created in app folder. In the app folder a sub folder has created its name is view and we get the header.php file in this file we can do the html code also. In this file we can create the dynamic code of the php file.

How to use of component -: After created component we use in other page means header file is a master file that are using lot of the pages for understanding component we take a example. First we create a another page that’s name is users.blade.php this is also created in view folder.

we will close in self close tag. here we have create a component file name then we give the this command

<x-component_name />

How to use component data in other page -: After creating component page we will use this component in other pages. For using component file we create a function on header.php file.

public $title="";  by default it is blank.
public function _construct($name)  or we can write the same component name here as like public function _construct($component_name)
{
  this -> title-> $component_name;
}

In this example we have created 3 file first is header.php file where we write thd function and second is the header.blade.php file where we created menu control or what we want to user other file and third is the user.blade.php file where we want to use our created component.

Now we will write the code on user.blade.php for applying the component. here we have created a variable in component and its name is users then we call in our pages.

<x-header component_name="users" />

Leave a Comment