view


Share data with all views

  • View Composer
    • Creating Views

      {tip} If you want to find out more about how to write Blade templates? Start by checking out the complete Blade documentation .

      The view contains the HTML of the application and separates the controller/application logic from the presentation logic. View files are stored in the resources/views directory. A simple view looks like this:

      <!-- 此视图文件位置 resources/views/greeting.blade.php -->
      <html>
        <body>
          <h1>Hello, {{ $name }}</h1>    
        </body>
      </html>

      The view file is located in resources/views/greeting.blade.php and can be returned using the global helper function view:

      Route::get('/', function () { 
         return view('greeting', ['name' => 'James']);
      });

      As you can see, the first parameter passed to the view helper corresponds to the name of the view file in the resources/views directory. The second parameter is an array of data that should be available to the view. In this case we pass the name variable which is displayed in the view using Blade syntax.

      Of course, view files can also be nested in subdirectories of the resources/views directory. The "dot" notation can be used to refer to nested views. For example, if your view is stored in resources/views/admin/profile.blade.php, you can reference it like this:

      return view('admin.profile', $data);

      Determine whether the view file exists

      If you need to determine whether the view file exists, you can use the View facade. If the view file exists, the exists method will return true:

      use Illuminate\Support\Facades\View;if (View::exists('emails.customer')) { 
         //
      }

      Create the first available view

      Using the first method, you can create the first view that exists in a given array view. This is useful if your application or third-party package you develop allows customizing or overriding views:

      return view()->first(['custom.admin', 'admin'], $data);

      Of course, you can also call this method through the View facade:

      use Illuminate\Support\Facades\View;return View::first(['custom.admin', 'admin'], $data);

      Passing parameters to the view

      As you saw in the previous example, you can pass a set of data To the view:

      return view('greetings', ['name' => 'Victoria']);

      When passing information this way, the data should be an array with key/value pairs. In the view, you can access each value using the corresponding key, for example <?php echo $key; ?>. As an alternative to passing the complete data array to the view helper function, you can add individual data fragments to the view using the with method:

      return view('greeting')->with('name', 'Victoria');

      Share data with all views

      If you need to share a piece of data with all views of the application, you can do this in the service provider's boot The method calls the share method of the view Facade. For example, you can add them to AppServiceProvider or generate a separate service provider for them:

      <?php
        namespace App\Providers;
        use Illuminate\Support\Facades\View;
        class AppServiceProvider extends ServiceProvider{   
           /**
           * Bootstrap any application services.
           *
           * @return void
           */   
           public function boot()   
            {      
              View::share('key', 'value');   
             }   
           /**
           * Register the service provider.
           *
           * @return void
           */    
           public function register()  
             {      
               // 
              }
           }

      View Composer

      A view composite is a callback or class method that is called when a view is rendered. If you want to bind data to a view every time it is rendered, a view composer can help you organize that logic into one place.

      In the following example, we will register the view composer in a service provider. Use the View facade to access the underlying Illuminate\Contracts\View\Factory contract implementation. By default, Laravel does not have a directory to store view composers. You need to re-create the directory according to your needs, for example: app/Http/View/Composers :

      <?php
         namespace App\Providers;
         use Illuminate\Support\Facades\View;
         use Illuminate\Support\ServiceProvider;
         class ViewServiceProvider extends ServiceProvider{    
            /**
           * Register bindings in the container.
           *
           * @return void
           */  
          public function boot()  
            {      
              // Using class based composers...        
              View::composer(        
                  'profile', 'App\Http\View\Composers\ProfileComposer'     
                );      
              // Using Closure based composers...        
              View::composer('dashboard', function ($view) {      
                    //  
                 });    
              }   
          /**
           * Register the service provider.
           *
           * @return void
           */   
           public function register()  
             {   
                  //   
              }
            }

      {note } Note that if you create a new service provider to store your code for registering the view composer, then you need to add this service provider to the of the configuration file config/app.php providers array.

      Now we have registered the view composer, and the ProfileComposer@compose method will be executed every time the profile view is rendered. So let’s define the class of the view composer:

      <?php
         namespace App\Http\View\Composers;
         use Illuminate\View\View;
         use App\Repositories\UserRepository;
         class ProfileComposer{   
           /**
           * The user repository implementation.
           *
           * @var UserRepository
           */ 
          protected $users;    
           /**
           * Create a new profile composer.
           *
           * @param  UserRepository  $users
           * @return void
           */    
          public function __construct(UserRepository $users)    {        
          // Dependencies automatically resolved by service container...        
          $this->users = $users;    }    
          /**
           * Bind data to the view.
           *
           * @param  View  $view
           * @return void
           */ 
           public function compose(View $view)   
            {     
               $view->with('count', $this->users->count());   
             }
          }

      The compose method of the view composer will be called before the view is rendered, and pass in an Illuminate\View \View instance. You can bind data to a view using the with method.

      {tip} All view composers will be resolved through the service container, so you can type-hint the dependencies that need to be injected in the constructor of the view composer.

      Add a view composer to multiple views

      By passing an array of views as the first argument to the composer method , add a view composer to multiple views:

      View::composer( 
         ['profile', 'dashboard'],    
         'App\Http\View\Composers\MyViewComposer'
        );

      composer The method also accepts the wildcard character *, which means adding a view composer to all views:

      View::composer('*', function ($view) {  
         //
      });

      View constructors

      Viewscreators are very similar to view compositors. The only difference is that the view constructor is executed immediately after the view is instantiated, while the view compositor is executed when the view is about to be rendered. Use the creator method to register the view constructor:

      View::creator('profile', 'App\Http\View\Creators\ProfileCreator');
      This article was first published on the LearnKu.com website.