lundi 26 juin 2017

Laravel 5.4 - Use the model instantiated from Controller in a View Composer

So lets say I have a view for a single project and in that view I have a form (uses a component) that opens up in a model. In order for that model component to even appear, I need that instance of the project. So for example

The route in web.php

Route::get('/projects/{project}', 'ProjectController@show');

My Project Controller

/* ProjectController show() method */
public function show(Project $project)
{
  return view('projects.show', compact('project'));
}

In my show blade template for that project, I have the following component to add a vendor to a project. As you can see I need to pass the instance of the project to that component.

@component('layouts.modals.add-project-vendor', ['project' => $project])

@endcomponent

I know you can attach data to a component, view, etc. using a view composer. I am utilizing the view composers throughout my project but I am gathering the data within the composer. What I want to be able to do is just use the instance of that project without even having to actually pass the project to the components. So for example.

View::composer(
   ['layouts.modals.add-project-vendor'],
   function($view){
    /* 
     * Somehow get that instance of the project 
     * that is already instantiated on the show page. And
     * send it to the component.      
     */
     $project = ; 
     $view->with(compact('project'));
   }
 );

So the desired outcome would just be able to call the following on a single project view and have that instantiated class passed into this component every time it is called. For example just:

@component('layouts.modals.add-project-vendor')

@endcomponent



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire