Inertia.js Laravel Adapter

Inertia.js 的 Laravel 适配器。(The Laravel adapter for Inertia.js.)

  • 所有者: inertiajs/inertia-laravel
  • 平台: BSD, Linux, Mac, Solaris, Windows
  • 许可证: MIT License
  • 分类:
  • 主题:
  • 喜欢:
    0
      比较:

Github星跟踪图

Inertia.js Laravel Adapter

To use Inertia.js you need both a server-side adapter (like this one) as well as a client-side adapter, such as inertia-vue. Be sure to also follow the installation instructions for the client-side adapter you choose. This documentation will only cover the Laravel adapter setup.

Installation

Install using Composer:

composer require inertiajs/inertia-laravel

Setup root template

The first step to using Inertia is creating a root template. We recommend using app.blade.php. This template should include your assets, as well as the @inertia directive.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <link href="{{ mix('/css/app.css') }}" rel="stylesheet">
    <script src="{{ mix('/js/app.js') }}" defer></script>
</head>
<body>

@inertia

</body>
</html>

The @inertia directive is simply a helper for creating our base div. It includes a data-page attribute which contains the inital page information. Here's what that looks like.

<div id="app" data-page="{{ json_encode($page) }}"></div>

If you'd like to use a different root view, you can change it using Inertia::setRootView().

Inertia\Inertia::setRootView('name');

Making Inertia responses

To make an Inertia response, use Inertia::render(). This function takes two arguments, the component name, and the component data (props).

use Inertia\Inertia;

class EventsController extends Controller
{
    public function show(Event $event)
    {
        return Inertia::render('Event', [
            'event' => $event->only('id', 'title', 'start_date', 'description'),
        ]);
    }
}

Alternatively, you can use the with() method to include component data (props):

use Inertia\Inertia;

class EventsController extends Controller
{
    public function show(Event $event)
    {
        return Inertia::render('Event')
            ->with('event', $event->only('id', 'title', 'start_date', 'description'));
    }
}

Following redirects

When making a non-GET Inertia request, via <inertia-link> or manually, be sure to still respond with a proper Inertia response. For example, if you're creating a new user, have your "store" endpoint return a redirect back to a standard GET endpoint, such as your user index page. Inertia will automatically follow this redirect and update the page accordingly. Here's a simplified example.

class UsersController extends Controller
{
    public function index()
    {
        return Inertia::render('Users/Index', ['users' => User::all()]);
    }

    public function store()
    {
        User::create(
            Request::validate([
                'first_name' => ['required', 'max:50'],
                'last_name' => ['required', 'max:50'],
                'email' => ['required', 'max:50', 'email'],
            ])
        );

        return Redirect::route('users');
    }
}

Note, when redirecting after a PUT, PATCH or DELETE request you must use a 303 response code, otherwise the subsequent request will not be treated as a GET request. A 303 redirect is the same as a 302 except that the follow-up request is explicitly changed to a GET request.

Sharing data

To share data with all your components, use Inertia::share($key, $data). This can be done both synchronously and lazily.

// Synchronously
Inertia::share('app.name', Config::get('app.name'));

// Lazily
Inertia::share('auth.user', function () {
    if (Auth::user()) {
        return [
            'id' => Auth::user()->id,
            'first_name' => Auth::user()->first_name,
            'last_name' => Auth::user()->last_name,
        ];
    }
});

// Multiple values
Inertia::share([
    // Synchronously
    'app' => [
        'name' => Config::get('app.name')
    ],
    // Lazily
    'auth' => function () {
        return [
            'user' => Auth::user() ? [
                'id' => Auth::user()->id,
                'first_name' => Auth::user()->first_name,
                'last_name' => Auth::user()->last_name,
            ] : null
        ];
    }
]);

You can also get shared data using the same method Inertia::share($key). If the key is not found, null is returned.

Accessing data in root template

There are situations where you may want to access your prop data in your root Blade template. For example, you may want to add a meta description tag, Twitter card meta tags, or Facebook Open Graph meta tags. These props are available via the $page variable.

<meta name="twitter:title" content="{{ $page['props']['event']->title }}">

Sometimes you may even want to provide data that will not be sent to your JavaScript component. You can do this using the withViewData() method.

return Inertia::render('Event', ['event' => $event])->withViewData(['meta' => $event->meta]);

You can then access this variable like a regular Blade variable.

<meta name="description" content="{{ $meta }}">

Asset versioning

One common challenge with single-page apps is refreshing site assets when they've been changed. Inertia makes this easy by optionally tracking the current version of your site assets. In the event that an asset changes, Inertia will automatically make a hard page visit instead of a normal ajax visit on the next request.

To enable automatic asset refreshing, first call the Inertia::version($version) method with your current asset version. We recommend putting this in a service provider.

Inertia::version($version);

If you're using Laravel Mix, you can use the mix-manifest.json for this. Here's an example of that using lazy evaluation.

Inertia::version(function () {
    return md5_file(public_path('mix-manifest.json'));
});

Finally, make sure you have versioning setup in your webpack.mix.js to enable asset cache busting.

主要指标

概览
名称与所有者inertiajs/inertia-laravel
主编程语言PHP
编程语言PHP (语言数: 4)
平台BSD, Linux, Mac, Solaris, Windows
许可证MIT License
所有者活动
创建于2019-03-07 18:06:54
推送于2025-09-09 19:28:31
最后一次提交
发布数64
最新版本名称v2.0.6 (发布于 )
第一版名称v0.1.0 (发布于 )
用户参与
星数2.3k
关注者数44
派生数265
提交数576
已启用问题?
问题数458
打开的问题数5
拉请求数167
打开的拉请求数5
关闭的拉请求数130
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?