I’m working on a project and I need to be able to execute a function from my app’s navigation menu. As far as I understand, all functions are executable from a view using wire:click, and this triggers the function from the associated controller.
Is there any way to create a global function (or several) so that they can be called from the navigation menu (which is always loaded) regardless of the view I’m in?
I hope I’ve explained myself.
I’ve tried to use Ajax, Providers, and more, but I don’t know which is the correct way to do it.
2
Answers
Providers
Create a Service
Inject Service in Components
Call from Navigation Menu
BroadcastService:
Create a BroadcastService
Emit Event from Navigation Menu
Listen for Event in Relevant Components
Here is the way I’ve done this in my laravel project (I’m not using livewire though, but I don’t see why this won’t work for you).
Create a service provider if you don’t have one for your site/app
Register the service provider in
config/app.php
And in the
boot
method of yourSiteServiceProvider
you can make global functions (available within all of your views)And in your view you can use that function like so
You could also make global variables.
In the
boot
method of thatSiteServiceProvider
you would have something like the followingAnd then you can use it in the view like
Having written most of this answer I now realize that this is not what you meant, you want to invoke a function by using a menu from anywhere in the site regardless of the view being served, but since I’ve already written this answer, maybe it’ll be useful to others…
One way you probably might be able to do this is putting the functions you want to be global into a trait, and then using that trait in all your view component classes.