Lolo
Lolo

Reputation: 537

Laravel 5.2 : Extending Blade by passing an object instead of a string

I want to add some blade directives.

I have in my service provider

Blade::directive('image', function ($media) {
    return "<?php echo {$media->getImageUrl()}; ?>";
});

The blade file contain

@image($media)

the $media variable is an object which use the Media model and which contains a public function getImageUrl()which return a string with the url of the image.

When I execute this code, I have this error message

Fatal error: Call to a member function getImageUrl() on string

The object passed in the Blade directive is considered as a string instead of Media object

Is there any way to use $media as an Mediaobject instead of a string ?

Upvotes: 3

Views: 1137

Answers (1)

tommy
tommy

Reputation: 3615

The curly braces should be around $media:

Blade::directive('image', function ($media) {
    return "<?php echo {$media}->getImageUrl(); ?>";
});

This compiles to:

<?php echo ($media)->getImageUrl(); ?>

As far as I know Blade directives only accept one expression as a string, including the function call braces. So the expression received by the directive is:

"($media)"

After changing directives you should clear the compiled views because Blade is caching the directives, so you would not see your changes taking affect.

Upvotes: 1

Related Questions