Inertia.js - modern monolith

Inertia - modern monolith



Do you know how to write SPA in Laravel? In short, not very convenient. Of course, you can use any front-end framework. Traditionally, it is customary to work with the Laravel + Vue.js bundle.



We write the entire frontend in Vue.js in resources/js, and use Laravel as an API.



Something like this:



Vue.js



// resources/js/pages/Users.vue
<template>
    <div v-for="user in users" :key="user.id">
        <a :href="`/users/${user.id}`">
          {{ user.name }}
        </a>
        <div>{{ user.email }}</div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                users: []
            }
        },
        methods: {
            async loadUsers() {
                const { data } = await this.$axios.get('/api/users');.
                this.users = data;
            }
        },
        async beforeMount() {
            await this.loadUsers();
        }
    }
</script>


Laravel



// routes/api.php
Route::get('/users', function index(User $user) {
    return $user->all();
});


That is, first we create an endpoint on the backend, and then on the front we receive data from it via an AJAX request.



? . . AJAX – . , Blade, , .



Blade, , :



return view('users', [
    'users' => $user->all()
]);


? , - -. Blade - . Laravel – API, - . .. ..



Inertia.js. , Blade. – Vue, React Svelte.



Laravel, Inertia.js Rails. . (, Symfony Yii2).



Vue.js Laravel. , .



return Inertia::render('Users', [
    'users' => $user->all()
]);


props.



props: {
  users: Array,
},


! .



- №2: (Vue Router, React Router) . – routes Vue- resources/js/Pages ( ). , Blade, , component.blade.php Component.vue.



: . AJAX-, , - . AppServiceProvider



Inertia::share([
    'errors' => function () {
        return Session::get('errors')
            ? Session::get('errors')->getBag('default')->getMessages()
            : (object) [];
    },
]);


Vue- $page.errors.



<div v-if="$page.errors.first_name">{{ $page.errors.first_name[0] }}</div>


.



, ( ), "", , .



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


, , – , – (1, 2).



, , , . - , .



. , , , . . , , .



, .



-, Inertia.js . , - Inertia.js, . , ( ).



-, Server-Side Rendering (SSR). , , , , SPA SSR, . , , , , . SSR, – Livewire. - .



-, Inertia.js – . – v0.1.9. , .



, web- .




All Articles