7. class ViewComposerServiceProvider extends ServiceProvider
{
public function register()
{
$view = $this->app->make('view');
$view->composer('welcome', AppHttpViewComposerUserComposer::class);
}
}
使い方
独自のServiceProviderを作成してconfig/app.phpに登録
8. use IlluminateViewView;
use IlluminateAuthAuthManager;
class UserComposer
{
private $auth;
public function __construct(AuthManager $authManager)
{
$this->auth = $authManager->guard('web');
}
public function compose(View $view)
{
$view->with([
'authUser' => $this->auth->user()
]);
}
}
AppHttpViewComposerUserComposer
27. namespace AppHttpResponder;
use IlluminateViewFactory;
use IlluminateHttpResponse;
use IlluminateContractsSupportResponsable;
class IndexResponder implements Responsable
{
public function __construct( Factory $view)
{
$this->view = $view;
}
public function toResponse($request): Response
{
return new Response(
$this->view->make( 'welcome' ), 200
);
}
}
Responderの実装はLaravel5.5から追加されたResponsable Interfaceを実装することでスッキリか
けます。