Skip to content

Instantly share code, notes, and snippets.

@abdumu
Last active January 21, 2022 12:26
Show Gist options
  • Save abdumu/603c89e43c1725fc40538e6ac4f3c5bd to your computer and use it in GitHub Desktop.
Save abdumu/603c89e43c1725fc40538e6ac4f3c5bd to your computer and use it in GitHub Desktop.
Helpers for Inertia and Laravel (translations, routes)
<?php
namespace App\Http\Controllers;
use Inertia\Inertia;
class AboutController extends Controller
{
public function __invoke()
{
return Inertia::render('About', [
'routes' => [
'register' => route('register'),
'terms' => route('terms'),
],
'translations' => getTrans([
'pages.about',
'features.title',
'features.body'
]),
]);
}
}
<?php
//...
//....
function getTrans($items)
{
return collect($items)->mapWithKeys(function ($item) {
return [$item => __($item)];
})->all();
}
<?php
//......
//......
class HandleInertiaRequests extends Middleware
{
//.....
//.....
public function share(Request $request)
{
return array_merge(parent::share($request), [
//....
//.....
'rootTranslations' => getTrans([
'pages.features',
'pages.help',
'pages.privacy_and_terms',
'pages.contact',
'pages.copyright',
//....
]),
'rootRoutes' => function () {
return [
'logout' => route('logout'),
'login' => route('login'),
'home' => route('home'),
];
},
]);
}
}
import { usePage } from '@inertiajs/inertia-vue3';
import { computed } from '@vue/runtime-core';
export function route(name, obj) {
const routes = computed(() => usePage().props.value.routes);
const rootRoutes = computed(() => usePage().props.value.rootRoutes);
let url = optional(routes.value)[name] || optional(rootRoutes.value)[name];
if (typeof url === undefined || !url || url === null) {
return name;
}
let params = url.matchAll(/__(\w+)\.(\w+)__/g);
for (let result of params) {
if (obj && obj.hasOwnProperty(result[1])) {
url = url.replace(result[0], obj[result[1]][result[2]]);
}
}
return url;
}
export function optional(variable, def = {}) {
return typeof variable === undefined || variable === null || variable === undefined ? def : variable;
}
export function t(key, replace) {
const translations = computed(() => {
return { ...(usePage().props.value.rootTranslations || {}), ...(usePage().props.value.translations || {}) };
});
let translation = optional(translations.value)[key] || key;
if (replace !== null && typeof replace !== 'undefined') {
const regex = new RegExp(':(' + Object.keys(replace).join('|') + ')', 'g');
return translation.replace(regex, (m, $1) => replace[$1] || m);
}
return translation.replace('&amp;', '&');
}
export default {
route,
optional,
t,
};
@abdumu
Copy link
Author

abdumu commented Nov 13, 2021

to use it in your vue3 components:

<script setup>
import { route, t } from '@/helpers.js';
</script>
<h4 class="font-bold my-2">{{ t('features.title') }}</h4>
<inertia-link :href="route('help')">{{ t('features.help') }}<inertia-link>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment