Component and Slot in Laravel

Web Developer Kaustubh
1 min readOct 13, 2019

--

Components are a reusable group of elements.

How to use Component and Slot (Example):-

1]Create one folder inside view and give a name e.g component.

2]Create file (questions-component.blade.php) inside component folder

resources
— views
— — component
— — — question-component.blade.php

3] code inside question-component.blade.php. Consider we are going to repeat this code over and over again in the project

//question-component.blade.php<div style="background: #cbcda8">
<div><b>Question:</b>-{{$question}}</div>
<div><b>Answer :</b>- {{$answer}}</div>
</div>
<div style="padding: 10px;"></div>

4]create another file where we can write code for display (index.blade.php)

@component('component.question-component')@slot('question')
What is earth?
@endslot
@slot('answer')
Earth is planet
@endslot
@endcomponent@component('component.question-component')@slot('question')
What is Laravel?
@endslot
@slot('answer')
Laravel is a web application framework with expressive, elegant syntax
@endslot
@endcomponent

In about code, we are calling component code which is defined in the question-component.blade.php file. Content defined inside slot will be placed inside the variable defined in the component.

e.g

@slot(‘question’)
What is earth?
@endslot

will be placed in {{$question}}

--

--

Web Developer Kaustubh

Sr.Web developer. love to code. PHP , Javascript, Mysql, Laravel, Jquey, git, project planing,Linux