그냥 사는 이야기

Laravel 5.3 Tutorial for Beginner - View Composers 본문

Development/Web

Laravel 5.3 Tutorial for Beginner - View Composers

없다캐라 2020. 1. 16. 10:43
반응형

Laravel 5.3 Tutorial for Beginner - View Composers

별도의 ServiceProvider 생성

php artisan make:provider ComposerServiceProvider

생성한 Service Provider Class를 등록해준다.

config/app.php
...
App\Providers\ComposerServiceProvider::class,
...

ProfileComposer 생성

Http에 ViewComposers 폴더를 생성하고 ProfileComposer.php 파일을 생성한다.

App/Http/ViewComposers/ProfileComposer.php
<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;

class ProfileComposer
{
    public function composer(View $view)
    {
        $view->with('married', random_int(0, 1));
        $view->with('test', 'say test');
    }
}
App/Providers/ComposerServiceProvider.php
...
use View;
...
public function boot()
{
    View::composer('pages.profile',
        'App\Http\ViewComposers\ProfileComposer');
}
web.php
Route::get('profile', 'PagesController@profile');
PageController.php
public function profile()
{
    return view('pages.profile');
}
profile.blade.php

이제 아래처럼 변수 사용이 가능하다.

{{ $married }}
{{ $test }}

하지만 이 변수들은 profile view에서만 가능하다.

settings view에서도 공유

App/Providers/ComposerServiceProvider.php
public function boot()
{
    View::composer(['pages.profile', 'pages.settings'],
        'App\Http\ViewComposers\ProfileComposer');
}
web.php
Route::get('settings', 'PagesController@settings');
PageController.php
public function settings()
{
    return view('pages.settings');
}
settings.blade.php 생성
@extends('layouts.master')

@section('body')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Profile</div>

                <div class="panel-body">
                    <p>{{ $married }} </p>
                    <p>{{ $test }}</p>
                    <p>{{ $age }}</p>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

추가

만약 ProfileComposer에서 create라는 함수를 추가한다면

App/Http/ViewComposers/ProfileComposer.php
public function create(View $view)
{
    $view->with('married', random_int(0, 1));
    $view->with('test', 'say test');
}
App/Providers/ComposerServiceProvider.php
public function boot()
{
    View::creator(['pages.profile', 'pages.settings'],
        'App\Http\ViewComposers\ProfileComposer');
}
Comments