Laravel Shared Data Package

Packages

January 17th, 2020

laravel-shared-data.png

Share data from your backend in JavaScript with Laravel Shared Data by Coderello. The API for this package is simple:

1// Facade
2SharedData::put([
3 'post' => Post::first(),
4 'app' => [
5 'name' => config('app.name'),
6 'environment' => config('app.env'),
7 ],
8]);
9 
10// Helper
11share([
12 'post' => Post::first(),
13 'app' => [
14 'name' => config('app.name'),
15 'environment' => config('app.env'),
16 ],
17]);

Which outputs data to JavaScript:

1window.sharedData = {
2 post: {
3 content: "...",
4 created_at: "...",
5 // ...
6 },
7 app: { /* ... */ }
8}

To output the configured JavaScript, add the @shared directive to your views:

1<html>
2<head>
3 @shared
4</head>
5</html>

If you want to configure the JavaScript object, you can publish and change the configuration:

1<?php
2 
3return ['js_namespace' => 'myCustomObjectName'];

This package has documentation available to help you get started, and you can view the source code on GitHub at coderello/laravel-shared-data.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.