πŸ“¦ An easy way to share the data from your backend to the JavaScript.

Overview

Laravel Shared Data

✨ Introduction

Laravel Shared Data provides an easy way to share the data from your backend to the JavaScript.

πŸš€ Quick start

  • Install the package:

    composer require coderello/laravel-shared-data
  • Include the @shared directive into your blade layout before all scripts.

  • Share the data from within Laravel:

    share(['user' => $user, 'title' => $title]);
  • Access the data from the JavaScript directly:

    const user = window.sharedData.user;
    const title = window.sharedData.title;
  • Or using the built-it global helper:

    const user = shared('user');
    const title = shared('title');

πŸ“– License

Laravel Shared Data is open-sourced software licensed under the MIT license.

Comments
  • Installation error

    Installation error

    Argument 1 passed to Coderello\SharedData\SharedData::__construct() must be of the type array, null given, called in D:\Work\Server\domains\luxwash\vendor\coderello\laravel-shared-data\src\Providers\SharedDataServiceProvider.php on line 41

    opened by extrem7 17
  • [Enh] Refactor Blade directive setup

    [Enh] Refactor Blade directive setup

    Blade directive setup has been refactored:

    • use Container::extend(), allowing lazy-load Blade compiler instantiation as well as correct functioning, when Blade package is not installed.

    • Add 'blade.compiler' to SharedDataServiceProvider::provides(), ensuring SharedData as well as its Blade directive will be registered correctly once Blade is requested from Container

    • Add the configuration for the Blade directive name, as 'shared' is too common and may conflict with other libraries.

    opened by klimov-paul 5
  • improve to prevent re assign window var

    improve to prevent re assign window var

    Hi

    As first thing I want congrat you for this package, this is very useful.

    Deeping more, the window variable should not allow to change in client side (unless necessary). With this current render the windows var can set to new value window.sharedData.username = 'new user'.

    My recommendation is to change the render function or maybe add new function as renderInmmutable() as like:

    public function renderInmmutable(): string
        {
          
            return '<script>window[\''.$this->getJsNamespace().'\'] =  (() => {
                                
                let output = '.$this->toJson().';
                                        
                return { 
                    data () {
                    return output;
                  }
                }
              })();</script>';
        }
    

    Then youcan call it as: window.sharedData.data()

    I appreciate your attention and feedback

    opened by j574144 4
  • Error trying to install

    Error trying to install

    Install error. issue with blade directive.

    InvalidArgumentException
    
      The directive name [] is not valid. Directive names must only contain alphanumeric characters and underscores.
    
      at vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php:684
        680β–•      */
        681β–•     public function directive($name, callable $handler)
        682β–•     {
        683β–•         if (! preg_match('/^\w+(?:::\w+)?$/x', $name)) {
      ➜ 684β–•             throw new InvalidArgumentException("The directive name [{$name}] is not valid. Directive names must only contain alphanumeric characters and underscores.");
        685β–•         }
        686β–•
        687β–•         $this->customDirectives[$name] = $handler;
        688β–•     }
    
          +19 vendor frames
      20  [internal]:0
          Illuminate\Foundation\Application::Illuminate\Foundation\{closure}()
    
          +5 vendor frames
      26  artisan:37
          Illuminate\Foundation\Console\Kernel::handle()
    
    opened by itmgmt-codeCorp 3
  • IE compatibility

    IE compatibility

    I found that your package make webpages not working on IE 11.

    And I found why, it's because in the function getJsHelper of the file src/SharedData.php, the JS code generated use a default parameter (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) in a function that is not compatible with IE.

    Here is a correction that I tried and works well on IE.

    window["'.$this->getJsHelperName().'"] = function(e) {
        var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
        return [window.sharedDataNamespace].concat("string" == typeof e ? e.split(".") : []).reduce(function(e, t) {
            return e === n || "object" != typeof e || void 0 === e[t] ? n : e[t]
        }, window)
    }
    

    Can I send you a pull request to make your package compatible with IE, or you want to do it yourself ?

    opened by yepzy 2
  • Key transformer

    Key transformer

    It would be handy to have an ability to specify the key transformer:

    SharedData::keyTransformer(function ($key) {
        return Str::camel($key);
    });
    

    So that:

    share(['auth_user' => auth()->user()]);
    

    Will be transformed into:

    {
        "authUser": {
            "id": 1,
            "firstName": "Ilya",
            "lastName": "Sakovich"
        }
    }
    
    opened by hivokas 2
  • Refactor `SharedData` configuration

    Refactor `SharedData` configuration

    Instead of storing entire $config array as internal property, configuration parameters are better to be split via particular fields. Especially, while there is only one configuration parameter - 'js_namespace'.

    This refactoring creates more clean code and allows easy creation of standalone SharedData instance if necessary.

    Attention: this is BC break change!

    opened by klimov-paul 2
  • Nonce CSP is not supported

    Nonce CSP is not supported

    There is no way to use nonce content security policy, since Coderello\SharedData\SharedData::render() method returns <script> with no way to inject additional data.

    public function render(): string
        {
            return '<script>'
                .'window["'.$this->getJsNamespace().'"]='.$this->toJson().';'
                .'window["sharedDataNamespace"]="'.$this->getJsNamespace().'";'
                .($this->getJsHelperEnabled() ? $this->getJsHelper().';' : '')
                .'</script>';
        }
    

    I think either class constructor or render method could accept nonce value.

    opened by mariusaustr 1
  • Problem with Spatie - Laravel-Ray

    Problem with Spatie - Laravel-Ray

    After installing spatie/laravel-ray, the @shared directive is not replaced anymore. Don't know if this is a bug in the spatie package or your package.

    The html source only show @shared instead of the ja script...

    opened by st3f 1
  • Erro with Laravel 8 + PHP 7.4: The directive name [] is not valid. Directive names must only contain alphanumeric characters and underscores.

    Erro with Laravel 8 + PHP 7.4: The directive name [] is not valid. Directive names must only contain alphanumeric characters and underscores.

    After install on Laravel 8.0 + PHP 7.4:

    `InvalidArgumentException

    The directive name [] is not valid. Directive names must only contain alphanumeric characters and underscores.

    at vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php:681 `

    Any idea?

    opened by silasrm 1
  • Delayed closures, interfaces implementation, tests refactoring

    Delayed closures, interfaces implementation, tests refactoring

    • Delayed closures (resolves #9)
    share(function() {
        return ['user' => auth()->user()];
    });
    
    // or
    
    share('user', function() {
        return auth()->user();
    });
    
    • Interfaces implementation (Arrayable, JsonSerializable, ArrayAccess)

    • Tests refactoring

    opened by hivokas 1
  • Always warning

    Always warning

    laravel.WARNING: Return type of Coderello\SharedData\SharedData::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/vagrant/code/liapp/vendor/coderello/laravel-shared-data/src/SharedData.php on line 203

    opened by asterism612 3
Releases(4.0.0)
Owner
Coderello
Open-source organization founded by @hivokas which offers numerous open-source packages for Laravel & JavaScript.
Coderello
Melek Berita Backend is a service for crawling data from various websites and processing the data to be used for news data needs.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Chacha Nurholis 2 Oct 9, 2022
Super simple share buttons for WordPress. No images, no css, no javascript

Developer Share Buttons A super lightweight social sharing solution using either the Web Share API or simple sharing links. Description A simple, cust

Grant Richmond 28 Nov 13, 2022
MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query and get result in a fastest way

Mysql Optimizer mysql optimizer also known as MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query

null 2 Nov 20, 2021
This composer plugin allows you to share your selected packages between your projects by creating symlinks

Composer - Shared Package Plugin This composer plugin allows you to share your selected packages between your projects by creating symlinks. All share

L'Etudiant 169 Sep 20, 2022
Share content between your websites.

Distributor Distributor is a WordPress plugin that makes it easy to distribute and reuse content across your websites β€” whether in a single multisite

10up 504 Jan 3, 2023
Tabler.io bundle for Symfony - a backend/admin theme for easy integration

Tabler Bundle for Symfony This repository contains a Symfony bundle, integrating the fantastic Tabler.io HTML Template into your Symfony project. It s

Kevin Papst 22 Jan 2, 2023
Task for GrumPHP that adds CSS linting support with stylelint. An easy way to enforce convention and avoid errors in your styles

grumphp-stylelint-task Installation Stylelint is a static analysis tool for styles. A mighty, modern linter that helps you avoid errors and enforce co

null 3 Apr 29, 2021
Share value objects that contain the same primitive value as a singleton

sharable-value-objects Share value objects that contain the same primitive value as a singleton. Singletons are kept under WeakReference objects. Inst

mpyw 5 Nov 14, 2021
Private groups to share messages, photos, videos, links with friends and family.

A truly private space for you and your friends What is Zusam ? Zusam (/tsuˈzam/) is a free and open-source way to self-host private forums for groups

Zusam 104 Dec 20, 2022
Optional package for Laravel to generate social share links.

Laravel Share Share links exist on almost every page in every project, creating the code for these share links over and over again can be a pain in th

Joren Van Hocht 466 Dec 21, 2022
Arc social share - A Social Bookmarking Plugin for Textpattern

arc_social_share A Social Bookmarking Plugin for Textpattern; easily add links for sharing content with numerous social networks. arc_social_share 1.4

Andy Carter 5 Nov 15, 2022
It is the latest version of private RAT called Xworm. I share this one for free, so leave the star⭐ to this repository

XWorm-RAT-cracked- It is the latest version of private RAT called Xworm. I share this one for free, so leave the star ⭐ to this repository COMPILING:

null 67 Jan 1, 2023
Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.DeepEqual().

Deeper Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.De

Joubert RedRat 4 Feb 12, 2022
A quick,easy and safe way of accessing Mysql-like databases from within a PHP program

Mysqli-Safe A simple, easy-to-use and secure way of accessing a Mysql database from within your PHP programs Mysqli-safe is a wrapper around the mysql

Anthony Maina Njoroge 2 Oct 9, 2022
The easiest way to match data structures like JSON/PlainText/XML against readable patterns. Sandbox:

PHP Matcher Library created for testing all kinds of JSON/XML/TXT/Scalar values against patterns. API: PHPMatcher::match($value = '{"foo": "bar"}', $p

Coduo 774 Dec 31, 2022
This package provides a simple and intuitive way to work on the Youtube Data API. It provides fluent interface to Youtube features.

Laravel Youtube Client This package provides a simple and intuitive way to work on the Youtube Data API. It provides fluent interface to Youtube featu

Tilson Mateus 6 May 31, 2023
Laravel Blog Package. Easiest way to add a blog to your Laravel website. A package which adds wordpress functionality to your website and is compatible with laravel 8.

Laravel Blog Have you worked with Wordpress? Developers call this package wordpress-like laravel blog. Give our package a Star to support us ⭐ ?? Inst

Binshops 279 Dec 28, 2022
Javascript-powered auto-completion functionality for your Symfony forms!

Symfony UX Autocomplete Javascript-powered auto-completion functionality for your Symfony forms! EXPERIMENTAL This component is currently experimental

Symfony 12 Dec 15, 2022
RRR makes structured data for WordPress really rich, and really easy.

Really Rich Results - JSON-LD Structured Data (Google Rich Results) for WordPress Search engines are putting more weight on structured data than ever

Pagely 22 Dec 1, 2022