Exchanging data between php and js
The purpose is to standardise the exchange of data between the php server side and js client side of your frontend application. There are two types of data exchange:
Global configuration data
Usage, from any of your project JavaScript files:
import { globalConf } from "@olmokit/core/data";
console.log(globalConf);
The object globalConf has following keys:
baseUrl: your project's base URL (environment aware), e.g.:http:/myproject.testcmsApiUrl: the CMS API base URL, e.g.https:/myproject.back.company.net/api,mediaUrl: the Media remote base URL, e.g.https:/myproject.back.company.net/storage/app/medialocale: the current locale (return value ofApp::getLocale())authenticated: a boolean to indicate whether the user is authenticated or not (return value ofAuthApi::check())
This data is automatically injected from the core component <x-assets-head /> that should be included in your src/layout/main/index.blade.php
Global custom data
Usage, from any of your project JavaScript files:
import { globalData } from "@olmokit/core/data";
console.log(globalData);
globalData is an object with the keys and data that you add from the core component <x-data key="mykey" :data="$data" /> where mykey can be any string and $data can be any php value (is automatically encoded with json_encode).
You can use <x-data /> component from any route, component or any blade template file. Note that if the same key is given from mulitple points the data will be overriden.
Examples
Using a custom .env variable
olmo.ts:
// ...config
env: {
extraVars: {
MY_KEY: "myvalue";
}
}
config/env.phpand .envare automatically updatedsrc/routes/myroute.blade.php:
<x-data key="myKey" :value="config('env.MY_KEY')" />
src/routes/index.js(or any other js file):
import { globalData } from "@olmokit/core/data";
console.log(globalData.myKey);
It should not happen but in case the env variable value is not updated on change run from the terminal npm run clear.
Accessing the currently authenticated user
This will expose the user without its token or token_active on the client side to prevent security risks.
src/layouts/main.blade.php:
<x-data key="user" :value="$userJs" />
src/routes/index.js(or any other js file):
import { globalData } from "@olmokit/core/data";
console.log(globalData.user);