PHPackages                             putyourlightson/laravel-datastar - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. putyourlightson/laravel-datastar

ActiveLibrary

putyourlightson/laravel-datastar
================================

A reactive hypermedia framework for Laravel.

1.0.0-RC.8(4mo ago)484831mitPHPPHP ^8.2CI passing

Since Jan 13Pushed 4mo ago3 watchersCompare

[ Source](https://github.com/putyourlightson/laravel-datastar)[ Packagist](https://packagist.org/packages/putyourlightson/laravel-datastar)[ GitHub Sponsors](https://github.com/bencroker)[ RSS](/packages/putyourlightson-laravel-datastar/feed)WikiDiscussions develop Synced today

READMEChangelogDependencies (5)Versions (17)Used By (0)

[![Stable Version](https://camo.githubusercontent.com/ba8d8ae02a592ff4522caa8194b150864a13097d4f5e0578380ff0a602a723bc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f707574796f75726c69676874736f6e2f6c61726176656c2d64617461737461723f6c6162656c3d737461626c65)](https://camo.githubusercontent.com/ba8d8ae02a592ff4522caa8194b150864a13097d4f5e0578380ff0a602a723bc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f707574796f75726c69676874736f6e2f6c61726176656c2d64617461737461723f6c6162656c3d737461626c65)[![Total Downloads](https://camo.githubusercontent.com/68d998b400cf7ee7d5533b8262cc4788c6baa8d9a15242f58e74cab5bc2a130d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f707574796f75726c69676874736f6e2f6c61726176656c2d6461746173746172)](https://packagist.org/packages/putyourlightson/laravel-datastar)

[![](https://camo.githubusercontent.com/76abd2cbbaf52a35eaf166ba03a6b8e5bc1520a8eb0b1d843b5bf818e746970a/68747470733a2f2f707574796f75726c69676874736f6e2e636f6d2f6173736574732f6c6f676f732f64617461737461722e737667)](https://camo.githubusercontent.com/76abd2cbbaf52a35eaf166ba03a6b8e5bc1520a8eb0b1d843b5bf818e746970a/68747470733a2f2f707574796f75726c69676874736f6e2e636f6d2f6173736574732f6c6f676f732f64617461737461722e737667)

Datastar Package for Laravel
============================

[](#datastar-package-for-laravel)

### A reactive hypermedia framework for Laravel.

[](#a-reactive-hypermedia-framework-for-laravel)

Warning

Updating from a previous version? View the [release notes](https://github.com/putyourlightson/laravel-datastar/blob/develop/CHANGELOG.md).

This package integrates the [Datastar hypermedia framework](https://data-star.dev/) with [Laravel](https://laravel.com/), allowing you to create reactive frontends driven by Blade views *or* controllers. It aims to replace the need for front-end frameworks such as React, Vue.js and Alpine.js + htmx, and instead lets you manage state and use logic from your Laravel backend.

Use-cases:

- Live search and filtering
- Loading more elements / Infinite scroll
- Paginating, ordering and filtering lists
- Submitting forms and running actions
- Pretty much anything to do with reactive front-ends

License
-------

[](#license)

This package is licensed for free under the MIT License.

Requirements
------------

[](#requirements)

This package requires [Laravel](https://laravel.com/) 11.0.0 or later.

Installation
------------

[](#installation)

Install manually using composer, then run the `artisan vendor:publish --tag=public` command to publish the public assets.

```
composer require putyourlightson/laravel-datastar:^1.0.0-RC.3

php artisan vendor:publish --tag=public
```

Overview
--------

[](#overview)

The Datastar package for Laravel allows you to handle backend requests by sending SSE events using [Blade directives](#blade-directives) in views *or* [using controllers](#using-controllers). The former requires less setup and is more straightforward, while the latter provides more flexibility.

Here’s a trivial example that toggles some backend state using the Blade view `datastar/toggle.blade.php` to handle the request.

```
{{-- main.blade.php --}}

        Enable

```

```
{{-- datastar/toggle.blade.php --}}

@php
    $enabled = $signals['enabled'] ?? false;
@endphp

@patchsignals(['enabled' => !$enabled])

@patchelements

        {{ $enabled ? 'Enable' : 'Disable' }}

@endpatchelements
```

Usage
-----

[](#usage)

Start by reading the [Getting Started](https://data-star.dev/guide/getting_started) guide to learn how to use Datastar on the frontend. The Datastar package for Laravel only handles backend requests.

Tip

The Datastar [VSCode extension](https://marketplace.visualstudio.com/items?itemName=starfederation.datastar-vscode) and [IntelliJ plugin](https://plugins.jetbrains.com/plugin/26072-datastar-support) have autocomplete for all `data-*` attributes.

When working with signals, note that you can convert a PHP array into a JSON object using the `json_encode` function.

```
{{-- main.blade.php --}}

@php
    $signals = ['foo' => 1, 'bar' => 2];
@endphp

```

### Datastar Helper

[](#datastar-helper)

The `datastar()` helper function is available in Blade views and returns a `Datastar` helper that can be used to generate action requests to the Datastar controller. The Datastar controller can either render a view, run a controller action, or call a route, each of which respond by sending an event stream containing zero or more SSE events.

[Signals](#signals) are also sent as part of the request, and are made available in Datastar views using the `$signals` variable.

#### `datastar()->view()`

[](#datastar-view)

Returns a `@get()` action request to render a view. The value should be a dot-separated path to a Blade view.

```
// Sends a `GET` request that renders a Blade view
{{ datastar()->view('path.to.view') }}
```

Variables can be passed in as a second argument, that will be available in the rendered view.

Warning

Variables are tamper-proof yet visible in the source code in plain text, so you should avoid passing in any sensitive data. Only primitive data types can be used as variables: **strings**, **numbers**, **booleans** and **arrays**. Objects and models *cannot* be used.

```
// Sends a `GET` request that renders a Blade view
{{ datastar()->view('path.to.view', ['foo' => 'bar']) }}
```

Options can be passed into the `@get()` action using a third argument.

```
// Sends a `GET` request that renders a Blade view
{{ datastar()->view('path.to.view', ['foo' => 'bar'], ['contentType' => 'form']) }}
```

#### `datastar()->action()`

[](#datastar-action)

Returns a `@post()` action request to run a controller action. The value should be an array with a controller class name as the first value and an action name as the second. A CSRF token is automatically generated and sent along with the request.

```
// Sends a `POST` request that runs a controller action
{{ datastar()->action(['MyController', 'update']) }}
```

Params can be passed in as a second argument, that will be available as arguments to the controller action

Warning

Params are tamper-proof yet visible in the source code in plain text, so you should avoid passing in any sensitive data. Only primitive data types can be used as params: **strings**, **numbers**, **booleans** and **arrays**. Objects and models *cannot* be used. Route-model binding works with controller actions.

```
// Sends a `POST` request that runs a controller action
{{ datastar()->action(['MyController', 'update'], ['foo' => 'bar']) }}
```

Options can be passed into the `@get()` action using a third argument.

```
// Sends a `POST` request that runs a controller action
{{ datastar()->action(['MyController', 'update'], ['foo' => 'bar'], ['contentType' => 'form']) }}
```

#### `datastar()->get()`

[](#datastar-get)

Returns a `@get()` action request that calls a route. The value must be a defined route.

```
// Sends a `GET` request to a route
{{ datastar()->get('/uri') }}
```

Options can be passed into the `@get()` action using a second argument.

```
// Sends a `GET` request to a route
{{ datastar()->get('/uri', ['contentType' => 'form']) }}
```

#### `datastar()->post()`

[](#datastar-post)

Works the same as [`datastar()->get()`](#datastar-get) but returns a `@post()` action request that calls a route. A CSRF token is automatically generated and sent along with the request.

```
// Sends a `POST` request to a route
{{ datastar()->post('/uri') }}
```

#### `datastar()->put()`

[](#datastar-put)

Works the same as [`datastar()->post()`](#datastar-post) but returns a `@put()` action request that calls a route.

```
// Sends a `PUT` request to a route
{{ datastar()->put('/uri') }}
```

#### `datastar()->patch()`

[](#datastar-patch)

Works the same as [`datastar()->post()`](#datastar-post) but returns a `@patch()` action request that calls a route.

```
// Sends a `PATCH` request to a route
{{ datastar()->patch('/uri') }}
```

#### `datastar()->delete()`

[](#datastar-delete)

Works the same as [`datastar()->post()`](#datastar-post) but returns a `@delete()` action request that calls a route.

```
// Sends a `DELETE` request to a route
{{ datastar()->delete('/uri') }}
```

### Blade Directives

[](#blade-directives)

Datastar Blade directives can patch and remove elements, patch signals, execute JavaScript and redirect the browser.

#### Patch Elements

[](#patch-elements)

The `@patchelements` directive allows you to [patch elements](https://data-star.dev/guide/getting_started#patching-elements) into the DOM.

```
{{-- main.blade.php --}}

        Search

```

```
{{-- datastar/search.blade.php --}}

@patchelements

        ...

@endpatchelements

@patchelements

        Search complete!

@endpatchelements
```

This will swap the elements with the IDs `results` and `search` into the DOM. Note that elements with those IDs **must** already exist in the DOM, unless a mode is specified (see below).

##### Element Patch Options

[](#element-patch-options)

Elements are patched into the DOM based on element IDs, by default. It’s possible to pass other modes and other [element patch options](https://data-star.dev/reference/sse_events#datastar-patch-elements) in as an argument.

```
@patchelements(['selector' => '#list', 'mode' => 'append'])
    A new list item
@endpatchelements
```

##### Automatic Element Patching

[](#automatic-element-patching)

Any elements output in a Datastar template (outside any `@patchelements` tags) will be automatically wrapped in a `@patchelements` directive. This makes it possible to write your views in a way that makes them more reusable.

```
{{-- datastar/search.blade.php --}}

```

The view above is the equivalent of writing:

```
{{-- datastar/search.blade.php --}}

@patchelements

@endpatchelements
```

While automatic element patching is convenient, it is less explicit and more restrictive (since [element patch options](#element-patch-options) cannot be used), so should only be used when appropriate.

#### Remove Elements

[](#remove-elements)

Elements can be removed from the DOM using the `@removeelements` directive, which accepts a CSS selector.

```
@removeelements('#list')
```

#### Patch Signals

[](#patch-signals)

The `@patchsignals` directive allows you to [patch signals](https://data-star.dev/guide/reactive_signals#patching-signals) into the frontend signals.

Note

Signals patches **cannot** be wrapped in `@patchelements` directives, since each patch creates a server-sent event which will conflict with the element’s contents.

```
{{- Sets the value of the `username` signal. -}}
@patchsignals(['username' => 'johnny'])

{{- Sets multiple signal values using an array of key-value pairs. -}}
@patchsignals(['username' => 'bobby', 'success' => true])

{{- Removes the `username` signal by setting it to `null`. -}}
@patchsignals(['username' => null])
```

#### Signal Patch Options

[](#signal-patch-options)

It’s possible to pass [signal patch options](https://data-star.dev/reference/sse_events#datastar-patch-signals) in as a second argument.

```
@patchsignals(['username' => 'johnny'], ['onlyIfMissing' => true])
```

### Executing JavaScript

[](#executing-javascript)

The `@executescript` directive allows you to send JavaScript to the browser to be executed on the front-end.

```
@executescript
    alert('Username is valid');
@endexecutescript
```

#### Execute Script Options

[](#execute-script-options)

It’s possible to pass execute script options in as an argument. They are applied to the `` tag that is appended to the DOM.

```
@executescript(['autoRemove' => true, 'attributes' => ['defer' => true]])
    alert('Username is valid');
@endexecutescript
```

### Redirecting

[](#redirecting)

The `@location` directive allows you to redirect the page by updating `window.location` on the front-end.

```
@location('/guide')
```

#### Location Options

[](#location-options)

It’s possible to pass location options in as a second argument. They are applied to the `` tag that is appended to the DOM.

```
@location('/guide', ['autoRemove' => true, 'attributes' => ['defer' => true]])
```

### Using Controllers

[](#using-controllers)

You can send SSE events from your own controller using the `sse()` helper. No routes are required, as Datastar will handle routing to the controller action you specify when using the [Datastar helper](#datastar-helper).

```
{{-- main.blade.php --}}

// Sends a `POST` request that runs a controller action
{{ datastar()->action(['MyController', 'update']) }}
```

```
namespace App\Http\Controllers;

use Illuminate\Routing\Controller;
use Symfony\Component\HttpFoundation\StreamedResponse;

class MyController extends Controller
{
    public function index(): StreamedResponse
    {
        $signals = sse()->readSignals();

        $enabled = $signals['enabled'] ?? false;

        sse()->patchSignals(['enabled' => !$enabled]);

        sse()->patchElements('
            ' . ($enabled ? 'Enable' : 'Disable') . '
        ');

        return sse()->getEventStream();
    }

    public function view(): StreamedResponse
    {
        sse()->renderView('path.to.view');

        return sse()->getEventStream();
    }
}
```

Controller actions *must* return a `StreamedResponse` created using the `getEventStream()` method.

### `sse()` Helper

[](#sse-helper)

The `sse()` helper provides methods to patch elements, patch signals, execute scripts, redirect the browser and render Datastar views.

#### `patchElements()`

[](#patchelements)

Patches elements into the DOM. Accepts [element patch options](#element-patch-options) as an optional second argument.

```
sse()->patchElements('New element');
```

#### `removeElements()`

[](#removeelements)

Removes elements that match the provided selector from the DOM.

```
sse()->removeElements('#list');
```

#### `patchSignals()`

[](#patchsignals)

Patches signals into the frontend. Accepts [signal patch options](#signal-patch-options) as an optional second argument.

```
sse()->patchSignals(['foo' => 1, 'bar' => 2]);
```

#### `executeScript()`

[](#executescript)

Executes JavaScript in the browser. Accepts [execute script options](#execute-script-options) as an optional second argument, which are applied to the `` tag that is appended to the DOM.

```
sse()->executeScript('alert("Hello, world!")');
```

#### `location()`

[](#location)

Redirects the browser by setting the location to the provided URI. Accepts [location options](#location-options) as an optional second argument, which are applied to the `` tag that is appended to the DOM.

```
sse()->location('/guide');
```

#### `renderView()`

[](#renderview)

Renders a Datastar view. Accepts the view path as the first argument and an optional array of variables as the second argument. The Blade view should output Datastar directives.

```
sse()->renderView('datastar.toggle', ['enabled' => true]);
```

### Signals

[](#signals)

Signals can be accessed within views rendered by Datastar using the signals variable, which is an array of signals received by the request that is automatically injected into the template.

Note

Signals patches **cannot** be wrapped in `@patchelements` directives, since each patch creates a server-sent event which will conflict with the element’s contents.

```

    Check

```

```
@php
    $username = $signals['username'];
@endphp
```

If you ever need to read the signals in a request that is *not* handled by the Datastar package, you can do so as follows.

```
@php
    $signals = sse()->readSignals();
@endphp
```

---

Created by [PutYourLightsOn](https://putyourlightson.com/).

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance74

Regular maintenance activity

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Total

16

Last Release

146d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/59428c6783d02d74c8778d9953ba84c35d3877ece53f5eb393689c052a9c97e4?d=identicon)[putyourlightson](/maintainers/putyourlightson)

---

Top Contributors

[![bencroker](https://avatars.githubusercontent.com/u/57572400?v=4)](https://github.com/bencroker "bencroker (120 commits)")[![icylace](https://avatars.githubusercontent.com/u/511030?v=4)](https://github.com/icylace "icylace (1 commits)")[![wilaak](https://avatars.githubusercontent.com/u/54738571?v=4)](https://github.com/wilaak "wilaak (1 commits)")

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/putyourlightson-laravel-datastar/health.svg)

```
[![Health](https://phpackages.com/badges/putyourlightson-laravel-datastar/health.svg)](https://phpackages.com/packages/putyourlightson-laravel-datastar)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
