You are going outside the boundaries of the intended uses for Blade Directive; custom directives are intended to return a string of executable php code which is evaluated whenever the template is rendered. AFAIK, any other code in your Closure will be evaluated only at compile time, so is effectively cached.
Consider using Blade Components instead; this is a class/view based approach which will allow you to pass in data via attributes, and within the class you can fetch/arrange the data you need in the View, e.g.
// view template that consumes the Component
<x-menu :name="$name" />
Your component class could do something like the following to locate the Model from the database and pass it to a view:
class Menu extends Component
{
public function __construct($name)
{
$this->name = $name;
}
public function render()
{
return view('components.menu', [
'menu' => Menu::where('name', $this->name)->first()
]);
}
}
As i have never used these before, i'm playing around with them and have run the following artisans, however am a little confused where i should be creating the Render Component Class which will have the two functions inside. Also assuming the render will need to be placed into my boot function as per the documentation?
php artisan make:component Menu
php artisan make:component Item
This represents the directory structure in the resources/views/components directory where you would have a render directory, and menu.blade.php and text.blade.php files. Similarly, the class would be located in a subdirectory of app/View/Components.
You can generate both class and view template using: