Programing

Laravel 5의 모든 뷰에 데이터를 전달하는 방법은 무엇입니까?

crosscheck 2020. 7. 30. 09:53
반응형

Laravel 5의 모든 뷰에 데이터를 전달하는 방법은 무엇입니까?


Laravel 5 응용 프로그램의 모든보기에서 일부 기본 데이터에 액세스 할 수 있기를 원합니다.

검색을 시도했지만 Laravel 4에 대한 결과 만 찾습니다. 여기에서 '모든 뷰와 데이터 공유'문서를 읽었 지만 어떻게해야하는지 이해할 수 없습니다. 다음 코드는 어디에 배치해야합니까?

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

당신의 도움을 주셔서 감사합니다.


이 목표는 다른 방법으로 달성 할 수 있습니다.

1. BaseController 사용

내가 물건을 세우는 것을 좋아하는 방식으로, 나는 BaseControllerLaravel의 자신을 확장 하는 수업을 만들고 Controller거기에 다양한 세계적인 것들을 세웁니다 . 다른 모든 컨트롤러 BaseController는 Laravel의 컨트롤러 아닌 확장됩니다 .

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

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

2. 필터 사용

전체 응용 프로그램 전체에서 모든 요청에 ​​대해 뷰에 대해 설정 한 것이 필요하다는 사실을 알고 있다면 요청 전에 실행되는 필터를 통해이를 수행 할 수도 있습니다. 이것이 Laravel의 User 객체를 처리하는 방법입니다.

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

또는

당신은 당신의 자신의 필터를 정의 할 수 있습니다

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

간단한 필터 호출을 통해 호출합니다.

버전 5에 따른 업데이트 *

3. 미들웨어 사용

View::share와 함께 사용middleware

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



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

4. View Composer 사용

또한 View Composer는 특정 데이터를 바인딩하여 다른 방식으로 볼 수 있도록 도와줍니다. 변수를 특정보기 나 모든보기에 직접 바인딩 할 수 있습니다. 예를 들어 요구 사항에 따라 view composer 파일을 저장하기 위해 고유 한 디렉토리를 만들 수 있습니다. Service를 통한 이러한 View Composer 파일은 View와의 상호 작용을 제공합니다.

View composer 방법은 다른 방식으로 사용할 수 있습니다. 첫 번째 예는 다음과 같습니다.

App\Http\ViewComposers디렉토리를 만들 수 있습니다 .

서비스 제공 업체

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
    public function boot() {
        view()->composer("ViewName","App\Http\ViewComposers\TestViewComposer");
    }
}

그런 다음이 공급자를 "제공자"섹션의 config / app.php에 추가하십시오.

TestViewComposer

namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;

class TestViewComposer {

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

ViewName.blade.php

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

이 방법은 특정보기에만 도움이 될 수 있습니다. 그러나 ViewComposer를 모든 뷰에 트리거하려면이 단일 변경 사항을 ServiceProvider에 적용해야합니다.

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
    public function boot() {
        view()->composer('*',"App\Http\ViewComposers\TestViewComposer");
    }
}

참고

라 라벨 문서

더 명확한 설명을 위해 라라 캐스트 에피소드

여전히 내 측면에서 분명하지 않은 것이 있으면 알려주세요.


고유 한 서비스 공급자 를 만들거나 ( ViewServiceProvider이름이 일반적 임) 기존 서비스 공급자 를 사용할 수 있습니다 AppServiceProvider.

선택한 공급자에서 코드를 부팅 방법에 넣으십시오.

public function boot() {
    view()->share('data', [1, 2, 3]);
}

이렇게하면 $data모든보기에서 변수에 액세스 할 수 있습니다.

도우미 대신 파사드를 사용하려면 파일 상단으로 변경 view()->하는 View::것을 잊지 마십시오 use View;.


나는 이것이 가장 쉬운 것을 발견했다. 새 제공자를 작성하고 '*'와일드 카드를 사용하여 모든보기에 첨부하십시오. 5.3에서도 작동합니다 :-)

<?php

namespace App\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function ($view)
        {
            $user = request()->user();

            $view->with('user', $user);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

가장 좋은 방법은 다음을 사용하여 변수를 공유하는 것입니다. View::share('var', $value);

다음을 사용하여 작성하는 데 문제가 있습니다 "*".

다음 접근법을 고려하십시오.

<?php
// from AppServiceProvider::boot()
$viewFactory = $this->app->make(Factory::class);

$viewFacrory->compose('*', GlobalComposer::class);

블레이드 뷰 예에서 :

  @for($i = 0; $i<1000; $i++)
    @include('some_partial_view_to_display_i', ['toDisplay' => $i])
  @endfor

무슨 일이야?

  • GlobalComposer클래스의 인스턴스가 1,000 사용 시간을 App::make.
  • 이벤트 composing:some_partial_view_to_display_i1000처리 됩니다.
  • 클래스 compose내부 함수 GlobalComposer는 1000 번 호출됩니다.

그러나 부분 뷰 some_partial_view_to_display_i는 구성된 변수와 관련이 GlobalComposer없지만 렌더링 시간이 크게 증가합니다.

가장 좋은 방법은?

View::share그룹화 된 미들웨어와 함께 사용 .

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

Route::group(['prefix' => 'api'], function (){

});

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

최신 정보

미들웨어 파이프 라인을 통해 계산 된 것을 사용 하는 경우 적절한 이벤트청취 하거나 파이프 라인의 맨 아래에 뷰 공유 미들웨어를 배치 할 수 있습니다.


설명서에서 :

일반적으로 서비스 제공자의 부트 메소드 내에서 share 메소드를 호출합니다. AppServiceProvider에 무료로 추가하거나 별도의 서비스 공급자를 생성하여 보관할 수 있습니다.

Marwelln에 동의 AppServiceProvider합니다. 부팅 기능에 넣으십시오 .

public function boot() {
    View::share('youVarName', [1, 2, 3]);
}

I recommend use an specific name for the variable, to avoid confussions or mistakes with other no 'global' variables.


The documentation is hear https://laravel.com/docs/5.4/views#view-composers but i will break it down

  1. Look for the directory app\Providers in the root directory of your application and create the file ComposerServiceProvider.php and copy and past the text below into it and save it.

    <?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()
        {
            //
        }
    }
    
  2. From the root of your application open Config/app.php and look for the Providers section in the file and copy and past this 'App\Providers\ComposerServiceProvider', to the array.

By doing this, we have created the Composer Service Provider. When you run your application with the view Profile like so http://yourdomain/something/profile, the service provider ComposerServiceProvider is called and the class App\Http\ViewComposers\ProfileComposer is instantiated calling the method Composer due to the code below inside the boot method or function.

 // Using class based composers...
 View::composer(
   'profile', 'App\Http\ViewComposers\ProfileComposer'
 );
  1. If you refresh your application you will get an error because the class App\Http\ViewComposers\ProfileComposer does not exist yet. Now lets create it.

Go to the directory path app/Http

  • Create the directory called ViewComposers

  • Create the file ProfileComposer.php.

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

Now go to your view or in this case Profile.blade.php and add

{{ $count }}

and that will show the count of users on the profile page.

To show the count on all pages change

// Using class based composers...
View::composer(
    'profile', 'App\Http\ViewComposers\ProfileComposer'
);

To

// Using class based composers...
View::composer(
    '*', 'App\Http\ViewComposers\ProfileComposer'
);

I think that the best way is with View Composers. If someone came here and want to find how can do it with View Composers way, read my answer => How to share a variable across all views?


Inside your config folder you can create a php file name it for example "variable.php" with content below:

<?php return [ 'versionNumber' => '122231', ];

Now inside all the views you can use config('variable.versionNumber') to call this variable.


The documentation is here https://laravel.com/docs/5.4/views#view-composers but i will break it down 1.Look for the directory Providers in your root directory and create the for ComposerServiceProvider.php with content


Laravel 5.6 method: https://laravel.com/docs/5.6/views#passing-data-to-views

Example, with sharing a model collection to all views (AppServiceProvider.php):

use Illuminate\Support\Facades\View;
use App\Product;

public function boot()
{
    $products = Product::all();
    View::share('products', $products);

}

참고URL : https://stackoverflow.com/questions/28608527/how-to-pass-data-to-all-views-in-laravel-5

반응형