Shone Tow
Shone Tow

Reputation: 536

Laravel - how to create custom 'with' method

The question is in the title. This is what I have been tried:

(this is just example. It all works in a regular way)

$my_data = 'some data';
return $this->with( 'my_data', $my_data );

Then I tried:

View::make('some-page')->withMyData();

I got this error:

ErrorException (E_UNKNOWN) 
Undefined offset: 0

tnx

Upvotes: 0

Views: 221

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

You definitely chose the wrong approach to pass something to every view. Use view composers instead.

View::composer('layout', function($view){
    $my_data = 'some data';
    $view->with('my_data', $my_data);
});

(layout would be the name of your view. Everytime it gets rendered the composer runs. You can also use wildcards * or an array of view names to target multiple views)

You can put this code in app/filters.php or create a new app/composers.php and include it at the end of app/start/global.php with:

require app_path().'/composers.php';

Edit

You can already use with* as an alternative to with('*'. So:

$view->with('my_data', $my_data);

Can be written as:

$view->withMyData($my_data);

Upvotes: 1

Related Questions