Laravel Data Views

Passing the Data Views

The data should be an array with the key/value pairs while passing the information in the following (return view(‘greeting’, [‘name’ => ‘John’]);) manner.

Inside the view, we can access each value by using its corresponding key easily, like <?php echo $key;?>

To pass a complete array of data to the view helper function as an alternative, we use the with() method for adding an individual piece to the views:

return view(‘greeting’, [‘name’ => ‘John’]);

Sharing Data with All Views

We need to share a piece of data with all kind of views that are provided by our application. We use the view façade's share method.

We should place calls to share it within a service provider`s boot method. We are free to add them to the AppServiceProvider or generate a separate service provider to them:

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

View Composers:

View composers are callbacks or class methods that are called when a view is provided.

 If we have data that we want to drive from a view each time, which is provided. A view composer can help us to organize logic into a single location.

For example, let`s register the view composers within a serviceprovider.

We will use the view façade to access the underlying Illuminate\Contracts\View\Factory contract implementation.

We have to remember that Laravel does not include a default directory for view composers. We are free to organize them; however, we wish.

We could create an App/Http/View/Composers directory:

<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
/**
     *
  *
      * @return void
      */
 public function register()
     {
         //
 }
 /**
      *     
      * @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) {
             //
         });
     }
 } 

    Note:

If we want to create a new service provider that contains our view composer registrations, we will need to add the service provider to the provider's array in the config/app.phpconfiguration file.

Now, we have registered the composer; the ProfileComposer@compose method will be executed each time, the profile view is being provided.

Let's define the composer class: 

<?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());
    }
}

Just before the view is provided, the composer's compose method is called with the Illuminate\View\View instance. We use with() method to bind data to the view.

  • All the view composers are resolved via the service container. We may type-hint any dependencies that we need within a composer's constructor.

Attaching a Composer to Multiple Views:

We attach a view composer to multiple views at once by passing an array of views as the first argument to the composer method:

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

The composer method also accepts the * character as a wildcard, it allow us to attach a composer to all views:

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

View Creators:

View creators are similar to view composers. They are executed immediately after the view is personalized of waiting, until the views are about to make. To register a view creator, we use the creator method:

View::creator('profile', 'App\Http\View\Creators\ProfileCreator');

Related Topics

Laravel Controller Middleware

Controller Middleware Middleware can be assigned to the controller`s routes in our route files: Route::get(‘profile’, ‘UserController@show’) ->middleware(‘auth’); It is more convenient to specify middleware within our controller`s constructor. Using the middleware method from our controller`s constructor,...

1 minute read.

Laravel Named Routes

Named Routes Named routes allow the suitable generation of URLs or redirects to specific routes. We specify a name for a route by changing the name method onto the route definition: Syntax:  Route::get(‘user/profile’, function () {...

2 minutes read.

Laravel Authentication

Authentication is a process of identifying user credentials. Laravel makes implementing authentication very simple. The authentication configuration file is located at config/auth.php that contains various documented options for adjusting the behavior of the authentication...

4 minutes read.

Laravel Displaying Data

Display data that is passed to our Blade views by enclosing the variable in curly braces. The following route is given below: Route::get('greeting', function () { return view('welcome', ['name' => 'rafia']); }); We display...

2 minutes read.

Raw SQL Queries

Raw SQL Queries: Laravel interact with databases by the variety of database back-ends with raw SQL, the fluent query builder, and the Eloquent ORM. Laravel supports four types of databases: MySQLPostgreSQLSQLiteSQL Server Configuration The database...

3 minutes read.

Laravel Advantages

Top 8 Advantages of Laravel The following advantages that Laravel offers, it is based upon designing a web application:- 1. Powerful Authentication: The Laravel PHP framework was developed with a purpose that can help...

2 minutes read.

Features of Laravel Framework

Top 8 Laravel Features Laravel has a very rich set of features that makes the speed of web development faster. The following features that serve the Laravel`s key points: Bundles: Bundles provide us a Modular Packaging...

2 minutes read.

Laravel Basic Controllers

Controllers group relate request handling logic into a single class. They are stored in the app/Http/Controllers directory. Basic Controllers Defining Controllers: The controllers extend the base controller class included with Laravel. The base class...

2 minutes read.

Database Migrations

Database Migrations in Laravel Introduction Migrations are version control for our database. It allows our team to modify and share the application`s database. Migrations are paired with schema builder to build an application`s database...

2 minutes read.

Laravel History and Versions

Laravel History Taylor Otwell created the Laravel; it was created as an attempt to provide an advanced alternative to the CodeIgniter framework. The CodeIgniter does not provide several features such as built-in support for...

3 minutes read.

Laravel Eloquent Database Relationships

Eloquent Relationships Laravel: Database tables are related to one another. Eloquent manages and work with easy relationships. It supports some different types of relationship, which are as follows: One to oneOne to manyMany...

8 minutes read.

Laravel Control Statements

Blade also provides convenient shortcuts for common control structure in PHP, such as conditional statements and loops. These shortcuts provide a very clean working with PHP structures, while also remain familiar to...

3 minutes read.

Laravel Route Parameters

Required Parameters: We need to capture segments of the URI within our route. We are going to see how to pass parameters through two or many views inside the closure function. Route::get('/home',...

2 minutes read.

Laravel First Packages

First Packages  Laravel provides the following ready to use packages: Cashier: It was introduced in Laravel 4.2 version, it provides an interface for managing subscription billing service, like handling coupons and generating invoices. SSH: It was...

2 minutes read.

Laravel Tutorial

Laravel Tutorial is a PHP based web-framework; it is used for developing high-end web applications by using significant syntax's. It has a substantial collection of tools and provides application architecture....

5 minutes read.

Laravel Resource Controllers

Laravel resource routing assigns the “CRUD” routes to a controller with the help of single line code. For E.g., If we wish to create a controller that handles all HTTP requests “photos” stored by...

4 minutes read.

Laravel Validation

Laravel provides a different way to validate the application`s incoming data. Laravel base controller class uses a ValidatesRequests that provides an easy method to validate incoming HTTP request with many powerful validation rules. Defining the...

5 minutes read.

Laravel vs Other Frameworks

Laravel is one of the top listing PHP framework. Some of the reasons which make Laravel top listing PHP framework that are as follows: Authorization Technique.Object-Oriented Libraries.Artisan.MVC Support.Security.Database Migration.Database Template Engine. In this Pie Chart distribution, we...

6 minutes read.

Laravel Uploading Files

Retrieving Uploaded Files We can access files from an Illuminate\Http\Request. By using the file method or using the dynamic properties. The file method returns an instance of the Illuminate\Http\UploadedFile class that extends the...

2 minutes read.

Laravel Data Views

Passing the Data Views The data should be an array with the key/value pairs while passing the information in the following (return view(‘greeting’, [‘name’ => ‘John’]);) manner. Inside the view, we...

4 minutes read.