├── tests ├── views │ └── app.blade.php ├── TestCase.php ├── ControllerTest.php ├── HelperTest.php ├── ServiceProviderTest.php └── ResponseTest.php ├── .gitignore ├── src ├── Controller.php ├── Inertia.php ├── Middleware.php ├── ServiceProvider.php ├── ResponseFactory.php └── Response.php ├── helpers.php ├── .php_cs.dist ├── phpunit.xml ├── composer.json ├── LICENSE └── readme.md /tests/views/app.blade.php: -------------------------------------------------------------------------------- 1 | @inertia 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | .DS_Store 3 | .phpunit.result.cache 4 | composer.lock 5 | -------------------------------------------------------------------------------- /src/Controller.php: -------------------------------------------------------------------------------- 1 | render($component, $props); 18 | } 19 | 20 | return $instance; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Inertia.php: -------------------------------------------------------------------------------- 1 | setUsingCache(false) 7 | ->setRiskyAllowed(true) 8 | ->setRules([ 9 | '@PHP70Migration' => true, 10 | '@PHP71Migration' => true, 11 | '@PSR2' => true, 12 | '@Symfony' => true, 13 | 'array_syntax' => ['syntax' => 'short'], 14 | 'increment_style' => ['style' => 'post'], 15 | 'no_multiline_whitespace_before_semicolons' => true, 16 | 'ordered_imports' => ['sortAlgorithm' => 'length'], 17 | 'semicolon_after_instruction' => false, 18 | 'strict_comparison' => true, 19 | 'yoda_style' => false, 20 | ]); 21 | -------------------------------------------------------------------------------- /tests/ControllerTest.php: -------------------------------------------------------------------------------- 1 | ['name' => 'Jonathan']]); 14 | 15 | $this->assertInstanceOf(Response::class, $response); 16 | $this->assertEquals([ 17 | 'page' => [ 18 | 'component' => 'User/Edit', 19 | 'props' => ['user' => ['name' => 'Jonathan']], 20 | 'url' => '', 21 | 'version' => null, 22 | ], 23 | ], $response->toResponse(new Request())->getData()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/HelperTest.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf(ResponseFactory::class, inertia()); 14 | } 15 | 16 | public function test_the_helper_function_returns_a_response_instance() 17 | { 18 | $this->assertInstanceOf(Response::class, inertia('User/Edit', ['user' => ['name' => 'Jonathan']])); 19 | } 20 | 21 | public function test_the_instance_is_the_same_as_the_facade_instance() 22 | { 23 | Inertia::share('key', 'value'); 24 | $this->assertEquals('value', inertia()->getShared('key')); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | tests 13 | 14 | 15 | 16 | 17 | src 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "inertiajs/inertia-laravel", 3 | "type": "library", 4 | "description": "The Laravel adapter for Inertia.js.", 5 | "keywords": ["laravel", "inertia"], 6 | "license": "MIT", 7 | "authors": [ 8 | { 9 | "name": "Jonathan Reinink", 10 | "email": "jonathan@reinink.ca", 11 | "homepage": "https://reinink.ca" 12 | } 13 | ], 14 | "autoload": { 15 | "psr-4": { 16 | "Inertia\\": "src" 17 | }, 18 | "files": [ 19 | "./helpers.php" 20 | ] 21 | }, 22 | "autoload-dev": { 23 | "psr-4": { 24 | "Inertia\\Tests\\": "tests/" 25 | } 26 | }, 27 | "require-dev": { 28 | "orchestra/testbench": "~3.0" 29 | }, 30 | "extra": { 31 | "laravel": { 32 | "providers": [ 33 | "Inertia\\ServiceProvider" 34 | ] 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Middleware.php: -------------------------------------------------------------------------------- 1 | header('X-Inertia')) { 16 | return $response; 17 | } 18 | 19 | if ($request->method() === 'GET' && $request->header('X-Inertia-Version') !== Inertia::getVersion()) { 20 | if ($request->hasSession()) { 21 | $request->session()->reflash(); 22 | } 23 | 24 | return Response::make('', 409, ['X-Inertia-Location' => $request->fullUrl()]); 25 | } 26 | 27 | if ($response instanceof Redirect && $response->getStatusCode() === 302 && in_array($request->method(), ['PUT', 'PATCH', 'DELETE'])) { 28 | $response->setStatusCode(303); 29 | } 30 | 31 | return $response; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Jonathan Reinink 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/ServiceProvider.php: -------------------------------------------------------------------------------- 1 | registerBladeDirective(); 15 | $this->registerRouterMacro(); 16 | $this->registerMiddleware(); 17 | } 18 | 19 | protected function registerBladeDirective() 20 | { 21 | Blade::directive('inertia', function () { 22 | return '
'; 23 | }); 24 | } 25 | 26 | protected function registerRouterMacro() 27 | { 28 | Router::macro('inertia', function ($uri, $component, $props = []) { 29 | return $this->match(['GET', 'HEAD'], $uri, '\Inertia\Controller') 30 | ->defaults('component', $component) 31 | ->defaults('props', $props); 32 | }); 33 | } 34 | 35 | protected function registerMiddleware() 36 | { 37 | $this->app[Kernel::class]->pushMiddleware(Middleware::class); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/ResponseFactory.php: -------------------------------------------------------------------------------- 1 | rootView = $name; 18 | } 19 | 20 | public function share($key, $value = null) 21 | { 22 | if (is_array($key)) { 23 | $this->sharedProps = array_merge($this->sharedProps, $key); 24 | } else { 25 | Arr::set($this->sharedProps, $key, $value); 26 | } 27 | } 28 | 29 | public function getShared($key = null) 30 | { 31 | if ($key) { 32 | return Arr::get($this->sharedProps, $key); 33 | } 34 | 35 | return $this->sharedProps; 36 | } 37 | 38 | public function version($version) 39 | { 40 | $this->version = $version; 41 | } 42 | 43 | public function getVersion() 44 | { 45 | return $this->version instanceof Closure ? App::call($this->version) : $this->version; 46 | } 47 | 48 | public function render($component, $props = []) 49 | { 50 | return new Response( 51 | $component, 52 | array_merge($this->sharedProps, $props), 53 | $this->rootView, 54 | $this->getVersion() 55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /tests/ServiceProviderTest.php: -------------------------------------------------------------------------------- 1 | assertArrayHasKey('inertia', $directives); 18 | $this->assertEquals('
', $directives['inertia']()); 19 | } 20 | 21 | public function test_route_macro_is_registered() 22 | { 23 | $route = Route::inertia('/', 'User/Edit', ['user' => ['name' => 'Jonathan']]); 24 | $routes = Route::getRoutes(); 25 | 26 | $this->assertNotEmpty($routes->getRoutes()); 27 | $this->assertEquals($route, $routes->getRoutes()[0]); 28 | $this->assertEquals(['GET', 'HEAD'], $route->methods); 29 | $this->assertEquals('/', $route->uri); 30 | $this->assertEquals(['uses' => '\Inertia\Controller@__invoke', 'controller' => '\Inertia\Controller'], $route->action); 31 | $this->assertEquals(['component' => 'User/Edit', 'props' => ['user' => ['name' => 'Jonathan']]], $route->defaults); 32 | } 33 | 34 | public function test_middleware_is_registered() 35 | { 36 | $kernel = App::make(Kernel::class); 37 | 38 | $this->assertTrue($kernel->hasMiddleware(Middleware::class)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /tests/ResponseTest.php: -------------------------------------------------------------------------------- 1 | ['name' => 'Jonathan']], 19 | 'app', 20 | '123' 21 | ); 22 | 23 | $response = $response->toResponse($request); 24 | $page = $response->getData()['page']; 25 | 26 | $this->assertInstanceOf(View::class, $response); 27 | $this->assertSame('User/Edit', $page['component']); 28 | $this->assertSame('Jonathan', $page['props']['user']['name']); 29 | $this->assertSame('/user/123', $page['url']); 30 | $this->assertSame('123', $page['version']); 31 | $this->assertSame('
'."\n", $response->render()); 32 | } 33 | 34 | public function test_xhr_response() 35 | { 36 | $request = Request::create('/user/123', 'GET'); 37 | $request->headers->add(['X-Inertia' => 'true']); 38 | 39 | $response = new Response( 40 | 'User/Edit', 41 | ['user' => ['name' => 'Jonathan']], 42 | 'app', 43 | '123' 44 | ); 45 | 46 | $response = $response->toResponse($request); 47 | $page = $response->getData(); 48 | 49 | $this->assertInstanceOf(JsonResponse::class, $response); 50 | $this->assertSame('User/Edit', $page->component); 51 | $this->assertSame('Jonathan', $page->props->user->name); 52 | $this->assertSame('/user/123', $page->url); 53 | $this->assertSame('123', $page->version); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Response.php: -------------------------------------------------------------------------------- 1 | component = $component; 22 | $this->props = $props; 23 | $this->rootView = $rootView; 24 | $this->version = $version; 25 | } 26 | 27 | public function with($key, $value = null) 28 | { 29 | if (is_array($key)) { 30 | $this->props = array_merge($this->props, $key); 31 | } else { 32 | $this->props[$key] = $value; 33 | } 34 | 35 | return $this; 36 | } 37 | 38 | public function withViewData($key, $value = null) 39 | { 40 | if (is_array($key)) { 41 | $this->viewData = array_merge($this->viewData, $key); 42 | } else { 43 | $this->viewData[$key] = $value; 44 | } 45 | 46 | return $this; 47 | } 48 | 49 | public function toResponse($request) 50 | { 51 | $only = array_filter(explode(',', $request->header('X-Inertia-Partial-Data'))); 52 | 53 | $props = ($only && $request->header('X-Inertia-Partial-Component') === $this->component) 54 | ? array_only($this->props, $only) 55 | : $this->props; 56 | 57 | array_walk_recursive($props, function (&$prop) { 58 | if ($prop instanceof Closure) { 59 | $prop = App::call($prop); 60 | } 61 | }); 62 | 63 | $page = [ 64 | 'component' => $this->component, 65 | 'props' => $props, 66 | 'url' => $request->getRequestUri(), 67 | 'version' => $this->version, 68 | ]; 69 | 70 | if ($request->header('X-Inertia')) { 71 | return new JsonResponse($page, 200, [ 72 | 'Vary' => 'Accept', 73 | 'X-Inertia' => 'true', 74 | ]); 75 | } 76 | 77 | return View::make($this->rootView, $this->viewData + ['page' => $page]); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Inertia.js Laravel Adapter 2 | 3 | To use [Inertia.js](https://github.com/inertiajs/inertia) you need both a server-side adapter (like this one) as well as a client-side adapter, such as [inertia-vue](https://github.com/inertiajs/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. 4 | 5 | ## Installation 6 | 7 | Install using Composer: 8 | 9 | ~~~sh 10 | composer require inertiajs/inertia-laravel 11 | ~~~ 12 | 13 | ## Setup root template 14 | 15 | 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. 16 | 17 | ~~~blade 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | @inertia 29 | 30 | 31 | 32 | ~~~ 33 | 34 | 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. 35 | 36 | ~~~blade 37 |
38 | ~~~ 39 | 40 | If you'd like to use a different root view, you can change it using `Inertia::setRootView()`. 41 | 42 | ~~~php 43 | Inertia\Inertia::setRootView('name'); 44 | ~~~ 45 | 46 | ## Add Inertia middleware 47 | 48 | Next, add the `Inertia\Middleware` middleware to your `web` middleware group, found in the `/app/Http/Kernel.php` file. This middleware monitors for asset changes, and also fixes an edge case with 302 redirects. Be sure to include this middleware *after* any session related middleware. 49 | 50 | ~~~php 51 | protected $middlewareGroups = [ 52 | 'web' => [ 53 | // ... 54 | \Inertia\Middleware::class, 55 | ] 56 | ]; 57 | ~~~ 58 | 59 | ## Making Inertia responses 60 | 61 | To make an Inertia response, use `Inertia::render()`. This function takes two arguments, the component name, and the component data (props). 62 | 63 | ~~~php 64 | use Inertia\Inertia; 65 | 66 | class EventsController extends Controller 67 | { 68 | public function show(Event $event) 69 | { 70 | return Inertia::render('Event', [ 71 | 'event' => $event->only('id', 'title', 'start_date', 'description'), 72 | ]); 73 | } 74 | } 75 | ~~~ 76 | 77 | Alternatively, you can use the `with()` method to include component data (props): 78 | 79 | ~~~php 80 | use Inertia\Inertia; 81 | 82 | class EventsController extends Controller 83 | { 84 | public function show(Event $event) 85 | { 86 | return Inertia::render('Event') 87 | ->with('event', $event->only('id', 'title', 'start_date', 'description')); 88 | } 89 | } 90 | ~~~ 91 | 92 | ## Following redirects 93 | 94 | When making a non-GET Inertia request, via `` 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. 95 | 96 | ~~~php 97 | class UsersController extends Controller 98 | { 99 | public function index() 100 | { 101 | return Inertia::render('Users/Index', ['users' => User::all()]); 102 | } 103 | 104 | public function store() 105 | { 106 | User::create( 107 | Request::validate([ 108 | 'first_name' => ['required', 'max:50'], 109 | 'last_name' => ['required', 'max:50'], 110 | 'email' => ['required', 'max:50', 'email'], 111 | ]) 112 | ); 113 | 114 | return Redirect::route('users'); 115 | } 116 | } 117 | ~~~ 118 | 119 | 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. 120 | 121 | ## Sharing data 122 | 123 | To share data with all your components, use `Inertia::share($key, $data)`. This can be done both synchronously and lazily. 124 | 125 | ~~~php 126 | // Synchronously 127 | Inertia::share('app.name', Config::get('app.name')); 128 | 129 | // Lazily 130 | Inertia::share('auth.user', function () { 131 | if (Auth::user()) { 132 | return [ 133 | 'id' => Auth::user()->id, 134 | 'first_name' => Auth::user()->first_name, 135 | 'last_name' => Auth::user()->last_name, 136 | ]; 137 | } 138 | }); 139 | 140 | // Multiple values 141 | Inertia::share([ 142 | // Synchronously 143 | 'app' => [ 144 | 'name' => Config::get('app.name') 145 | ], 146 | // Lazily 147 | 'auth' => function () { 148 | return [ 149 | 'user' => Auth::user() ? [ 150 | 'id' => Auth::user()->id, 151 | 'first_name' => Auth::user()->first_name, 152 | 'last_name' => Auth::user()->last_name, 153 | ] : null 154 | ]; 155 | } 156 | ]); 157 | ~~~ 158 | 159 | You can also get shared data using the same method `Inertia::share($key)`. If the key is not found, `null` is returned. 160 | 161 | ## Accessing data in root template 162 | 163 | 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. 164 | 165 | ~~~blade 166 | 167 | ~~~ 168 | 169 | 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. 170 | 171 | ~~~php 172 | return Inertia::render('Event', ['event' => $event])->withViewData(['meta' => $event->meta]); 173 | ~~~ 174 | 175 | You can then access this variable like a regular Blade variable. 176 | 177 | ~~~blade 178 | 179 | ~~~ 180 | 181 | ## Asset versioning 182 | 183 | 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. 184 | 185 | 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. 186 | 187 | ~~~php 188 | Inertia::version($version); 189 | ~~~ 190 | 191 | If you're using Laravel Mix, you can use the `mix-manifest.json` for this. Here's an example of that using lazy evaluation. 192 | 193 | ~~~php 194 | Inertia::version(function () { 195 | return md5_file(public_path('mix-manifest.json')); 196 | }); 197 | ~~~ 198 | 199 | Finally, make sure you have [versioning](https://laravel.com/docs/mix#versioning-and-cache-busting) setup in your `webpack.mix.js` to enable asset cache busting. 200 | --------------------------------------------------------------------------------