Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-widgetize

> 前端框架
Open source

A minimal package to help you make your laravel application cleaner and faster.

911 stars0 likes4 views
WebsiteGitHub

About

A minimal package to help you make your laravel application cleaner and faster.

Laravel Widgetize :ribbon::ribbon: "cleaner code" :heavy_plus_sign: "easy caching" :ribbon::ribbon:

Built with :heart: for every smart laravel developer


  • :flashlight: Overview

    • What is a widget object ?
    • When to use the widget concept?
    • Technical Features
  • :wrench: Installation

  • :earth_africa: Global Configuration

  • :blue_car: Per Widget Configuration

    • public $template (optional)
    • public $cacheLifeTime (optional)
    • public $cacheTags (optional)
    • public $cacheView (optional)
    • public $controller (optional) Advanced
    • public $presenter (optional) Advanced
    • public function extraCacheKeyDependency (optional) Advanced
    • public function cacheKey (optional) Advanced
  • :bulb: Usage and Example

    • How to make a widget class
    • How to use a widget class
    • What is a slot?
    • How to define a slot
    • How to use the slot

More readings:

  • :shipit: Some Theory for Experts

    • Article about widgetize and S in Solid Design Patterns
    • Article about widgetize and O in Solid Design Patterns
  • :star: Your Stars Makes Us Do More

This page may look long and boring to read at first, but bear with me!!!

I bet if you read through it you won't get disappointed at the end.So let's Go... :horse_racing:


Installation: :arrow_down:

bash
composer require imanghafoori/laravel-widgetize

:electric_plug: (For Laravel [ // for laravel 5.4 and below Imanghafoori\Widgets\WidgetsServiceProvider::class, ];


__Publish your config file__
``` bash
php artisan vendor:publish

:fire: And you will be on fire!:fire:

bash
php artisan make:widget MySexyWidget

…

 php
public function compose(View $view)
{
    $view->with('count', $this->users->count());
}

3- They offer no caching out of the box.


:bulb: Sample Code:

How to generate a widget?

You can use : php artisan make:widget MyWidget to make your widget class.

Sample widget class :

php
namespace App\Widgets;

class MyWidget
{
    // The data returned here would be available in widget view file automatically.
    public function data($my_param=5)
    {
        // It's the perfect place to query the database for your widget...
        return Product::orderBy('id', 'desc')->take($my_param)->get();

    }
}

App\Widgets\MyWidgetView.blade.php :

blade

  @foreach($data as $product)
    

      {{ $product->title }}
    

  @endforeach
  
  Note that it is perfectly ok to use an other widget here 
  @widget('AnOtherWidget')

Ok, Now it's done! We have a ready to use widget. let's use it...

Then how to use that widget?

In a normal day to day view (middle-end):

blade

    
    
        
Hello {{ auth()->user()->username }} 
 

        @widget('RecentProductsWidget') 
        
    

An other way to think of @widget() in your blade files :

All of us, more or less have some ajax experience. One scenario is to lazy load a page partial after
the page has been fully loaded.
You can think of @widget() as an ajax call from "middle-end" to the "back-end" to load a piece of HTML
into the page.

What is the slot?

Slots help you position your HTML or blade code in a widget, and allow the parent widget to arrange it, and improves your widget reusability.

How to define a slot?

To use the slot, you should use @slotWidget instead of @widget and close the directive @endSlotWidget, Then define your slot middle of it. Look at the syntax:

blade
@slotWidget('MyWidget')
    @slot('message')
        
Hello {{ auth()->user()->username }} 

    @endSlot
@endSlotWidget

also, you can pass your data:

blade
@slotWidget('MyWidget', [$a, $b])
...

How to use the slot?

App\Widgets\MyWidgetView.blade.php :

blade

…

php
expire_widgets(['someTag', 'tag1']);

This causes all the widgets with 'someTag' or 'tag1' to be refreshed.

Note: Tagging feature works with ALL the laravel cache drivers including 'file' and 'database'.

public $cacheView

In case you want your view to be real-time but your controller results to be cached, set this to false. defalut value is true.

public function cacheKey

If you want to explicitly define the cache key used to store the html result of your widget, you can implement this method.

php
    public function cacheKey($args)
    {
        return 'user_widget_'.$args['user_id'];
    }

public function extraCacheKeyDependency

It is important to note that if your final widget HTML output depends on PHP's super global variables and you want to cache it,Then they must be included in the cache key of the widget.

php
namespace App\Widgets;

class MyWidget
{

    public function data()
    {
        $id = request('order_id'); // here we are using a request parameter to fetch database...
        return Product::where('order_id', $id)->get();
    }
    

    public function extraCacheKeyDependency()
    {
        // so the value of this parameter should be considered for caching.
        return request()->get('order_id');
    }
    
}

You may want to look at the source code and read the comments for more information.

Tip: If you decide to use some other template engine instead of Blade it would be no problem.

:book: Solid Design Pattern

You can Find more information in the article below : It is a 3 minutes read.

Single Responsibility Prinsiple


Q&A

Q&A:How to expose only a widget HTML content from a url ?

php
Route::widget('/some-url', 'MyWidget', 'MyRouteName1'); // <-- exposes HTML
// or
Route::jsonWidget('/my-api','MyWidget', 'MyRouteName2'); // <-- exposes json

A GET request to /some-url/{a}/{b} will see the widget. a and b parameters are passed to widget controller.

jsonWidget will expose the cached data returned from the widget's controller.


Q&A:How to reference widget controllers from routes ?

This way you can also expose your data as json for client-side apps.

php
Route::get('/api/products/{id}', '\App\Widgets\MyWidget@data');

* It is important to put \ before App when you want to refer to a class outside the Http\Controller folder.


:raising_hand: Contributing

If you find an issue, or have a better way to do something, feel free to open an issue or a pull request. If you use laravel-widgetize in your open source project, create a pull request to provide it's url as a sample application in the README.md file.

:exclamation: Security

If you discover any security related issues, please use the security tab instead of using the issue tracker.

:star: Your Stars Make Us Do More :star:

As always if you found this package useful and you want to encourage us to maintain and work on it. Just press the star button to declare your willing.

Star History

More from the author:

Laravel Microscope

:gem: It automatically find bugs in your laravel app

  • https://github.com/imanghafoori1/laravel-microscope

Laravel middlewarize

:gem: You can put middleware on any method calls.

  • https://github.com/imanghafoori1/laravel-middlewarize

Laravel HeyMan

:gem: It allows to write expressive code to authorize, validate and authenticate.

  • https://github.com/imanghafoori1/laravel-heyman

Laravel Terminator

:gem: A minimal yet powerful package to give you opportunity to refactor your controllers.

  • https://github.com/imanghafoori1/laravel-terminator

Laravel AnyPass

:gem: It allows you login with any password in local environment only.

  • https://github.com/imanghafoori1/laravel-anypass

Great spirits have always encountered violent opposition from mediocre minds.

"Albert Einstein"

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPdesign-patternhtml-minificationhtml-minifierlaravel

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架