How to Create Widgets in Laravel Application?

By Hardik Savani November 5, 2023 Category : Laravel Pingpong

In this post you can learn how to create your own widgets in laravel 5.2, First thing why we are create widgets, So we can use widget because when we can create re-usable code, for example you have manu items and comes from database like home, items, products, aboutus, contact us etc. you require to display in top header, in sidebar and in footer. But in top you have to just display home and aboutus, and in sidebar products and items same that way in footer. So, basically you have to display in three place in your site page. widgets through you can make one function or view and call just one widget at time and get diffrence manu. so that's why we have to use widgets. This is for example but you can use more.

In, following example you can see, how to implement widgets packages and how to make widgets in laravel and how to use in widgtes view. So follow step and use in your side widgets:

Step 1: Installation

Open your composer.json file and add bellow line in required package.

"pingpong/widget" : "~2.0"

Then, run command composer update

Now open config/app.php file and add service provider and aliase.

'providers' => [

....

'Pingpong\Widget\WidgetServiceProvider',

],

'aliases' => [

....

'Widget' => 'Pingpong\Widget\WidgetFacade'

],

Step 2: Create app/widgets.php

In this step you have to create new file widgets.php(app/widgets.php) in your app directory and put bellow code in that file.

class MunuBarWidget {

public function namageMenu($value)

{

switch ($value) {

case 'homepage':

$html = '<ul>';

$html = $html.'<li>Homepage 1</li>';

$html = $html.'<li>Homepage 2</li>';

$html = $html.'<li>Homepage 3</li>';

$html = $html.'</ul>';

break;

case 'sidebar':

$html = '<ul>';

$html = $html.'<li>SideBar 1</li>';

$html = $html.'<li>SideBar 2</li>';

$html = $html.'<li>SideBar 3</li>';

$html = $html.'</ul>';

break;

default:

$html = '<ul>';

$html = $html.'<li>Default 1</li>';

$html = $html.'<li>Default 2</li>';

$html = $html.'<li>Default 3</li>';

$html = $html.'</ul>';

break;

}

return $html;

}

}

Widget::register('menubar', 'MunuBarWidget@namageMenu');

Step 3: create route

Next simple you need to create route in your routes.php file:

Route::get('/', function () {

return view('welcome');

});

Step 4: Use Widgets in view

In Last step you can use widgets using Widget facade. so you have to open welcome.blade.php(resources/views/welcome.blade.php) file and put bellow code:

<html>

<head>

<title>Laravel 5.2</title>

</head>

<body>

<div class="container">

<div class="content">

<h1>HomePage</h1>

{!! Widget::menubar('homepage') !!}

<h1>SideBar</h1>

{!! Widget::menubar('sidebar') !!}

</div>

</div>

</body>

</html>

Now open your browser and check......

Tags :
Shares