Laravel Views

Laravel Views

Are stored in the resources/views directory.

Creating Views

<!-- View stored in resources/views/greeting.blade.php -->

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>
Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});
Return view('admin.profile', $data);

Passing Data To Views

Return view('greetings', ['name' => 'Victoria']);
Return view('greeting')->with('name', 'Victoria');

Ou may use the with method to add individual pieces of data to the view.

View Composers

View Composers — Are callbacks or class methods that are called when a view is rendered.

If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using class based composers...
        View::composer(
            'profile', 'App\Http\ViewComposers\ProfileComposer'
        );

        // Using Closure based composers...
        View::composer('dashboard', function ($view) {
            //
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
<?php

namespace App\Http\ViewComposers;

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());
    }
}
  • Laravel does not include a default directory for view composers.
  • You are free to organize them however you wish.
  • All view composers are resolved via the service container, so you may type-hint any dependencies you need within a composer's constructor.
  • App/Http/ViewComposers.

Laravel Views — Structure map

Clickable & Draggable!

Laravel Views — Related pages: