Asked  7 Months ago    Answers:  5   Viewed   39 times

I want to have some default data accessible in all views in my Laravel 5 application.

I have tried to search for it but only find results for Laravel 4. I have read the documentation 'Sharing Data With All Views' here but I can't understand what to do. Where should the following code be placed?

View::share('data', [1, 2, 3]);

Thanks for your help.

 Answers

59

This target can achieve through different method,

1. Using BaseController

The way I like to set things up, I make a BaseController class that extends Laravel’s own Controller, and set up various global things there. All other controllers then extend from BaseController rather than Laravel’s Controller.

class BaseController extends Controller
{
  public function __construct()
  {
    //its just a dummy data object.
    $user = User::all();

    // Sharing is caring
    View::share('user', $user);
  }
}

2. Using Filter

If you know for a fact that you want something set up for views on every request throughout the entire application, you can also do it via a filter that runs before the request — this is how I deal with the User object in Laravel.

App::before(function($request)
{
  // Set up global user object for views
  View::share('user', User::all());
});

OR

You can define your own filter

Route::filter('user-filter', function() {
    View::share('user', User::all());
});

and call it through simple filter calling.

Update According to Version 5.*

3. Using Middleware

Using the View::share with middleware

Route::group(['middleware' => 'SomeMiddleware'], function(){
  // routes
});



class SomeMiddleware {
  public function handle($request)
  {
    View::share('user', auth()->user());
  }
}

4. Using View Composer

View Composer also help to bind specific data to view in different ways. You can directly bind variable to specific view or to all views. For Example you can create your own directory to store your view composer file according to requirement. and these view composer file through Service provide interact with view.

View composer method can use different way, First example can look alike:

You could create an AppHttpViewComposers directory.

Service Provider

namespace AppProviders;
use IlluminateSupportServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
    public function boot() {
        view()->composer("ViewName","AppHttpViewComposersTestViewComposer");
    }
}

After that, add this provider to config/app.php under "providers" section.

TestViewComposer

namespace AppHttpViewComposers;

use IlluminateContractsViewView;

class TestViewComposer {

    public function compose(View $view) {
        $view->with('ViewComposerTestVariable', "Calling with View Composer Provider");
    }
}

ViewName.blade.php

Here you are... {{$ViewComposerTestVariable}}

This method could help for only specific View. But if you want trigger ViewComposer to all views, we have to apply this single change to ServiceProvider.

namespace AppProviders;
use IlluminateSupportServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
    public function boot() {
        view()->composer('*',"AppHttpViewComposersTestViewComposer");
    }
}

Reference

Laravel Documentation

For Further Clarification Laracast Episode

If still something unclear from my side, let me know.

Wednesday, March 31, 2021
 
Tucker
answered 7 Months ago
43

Here is how I solved this.

  1. In .env, use the 'stack channel' for logging (i.e. 'LOG_CHANNEL=stack')
  2. Add a 'tap' to a driver in configlogging.php

    'single' => [
        'driver' => 'single',
        'tap' => [AppLoggingCustomizeFormatter::class],
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
    ]
    
  3. Create AppLoggingCustomizeFormatter:

    namespace AppLogging;
    
    class CustomizeFormatter
    {
        public function __invoke($logger)
        {
            foreach ($logger->getHandlers() as $handler) {
                $handler->pushProcessor(function ($record) {
                    $record['extra']['ip'] = Request::getClientIp();
                    $record['extra']['path'] = Request::path();
    
                    return $record;
                });
            }
        }
    }
    
Wednesday, March 31, 2021
 
PeanutsMcgee
answered 7 Months ago
33

Recommended approach if you put here only methods (not classes):

  1. Create file anywhere you want
  2. In composer.json make sure you add this file to files key inside autoload like this:

    "autoload": {
        // here other autoload things
    
        "files": ["app/Helpers/AnythingHelper.php"]
    },
    
  3. Run composerdump-autoload`

For classes obviously you should use standard PSR-4 autoloading

Wednesday, March 31, 2021
 
zhartaunik
answered 7 Months ago
42

The simple answer is that you don't do this. Password fields should rarely be pre-filled and so because it's not a common occurrence Laravel doesn't support it.

However, if you really want to do this you can use Form::input():

Form::input('password', 'name', 'value')
Saturday, May 29, 2021
 
macha
answered 5 Months ago
85

After re-reading the docs, it is clear that this is intended behaviour. The docs say

As an alternative to mocking, you may use the Event facade's fake method to prevent all event listeners from executing.

As described in a comment, I have to create two tests. One for making sure that the event has been fired and contains the expected data and a second one for making sure that the event listeners get fired.

So, first Test:

Event::fake();

$order = factory(Order::class)->make();

event(new PaymentWasCompleted($order));

Event::assertDispatched(PaymentWasCompleted::class, function ($e) use ($order) {
    return $e->order->id === $order->id;
});

Second test:

Queue::fake();

$order = factory(Order::class)->make();

event(new PaymentWasCompleted($order));

Queue::assertPushed(GenerateInvoiceJob::class, function ($job) use ($order) {
    return $job->order->id === $order->id;
});

As expected, this tests pass.

Saturday, May 29, 2021
 
Amber
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :