Pass an object to a controller from a view in Laravel

1

I'm trying to find a way to pass an object from a view to a controller in Laravel 5.2.

The view contains a Form and the $user object is accessible in the view.

I would like to know some way to access the $user object in the controller that is called when the form submit is done.

The view from where $user is accessible:

credential.blade.php:

<div id="container" align="center">
     {{ Form::open(array('action' => 'UsersController@setCredentials', 'method' => 'POST' )) }}

     {{ Form::close() }}
</div>

routes.php

Route::post('/credential', 'UsersController@setCredentials');

The driver where I would like to be able to access the $ user object.

UsersController.php

public function setCredentials() {

  $this->user= $user;
}
    
asked by David 05.08.2016 в 17:20
source

2 answers

1

You can send the id of the user object in a hidden field

<input type="hidden" name="id" value="{{$user->id}}">

and in your controller you should only do this (assuming your model is called User)

 $user = User::find(Request::input('id'));
    
answered by 05.08.2016 / 17:51
source
1

You can add the model directly to the URL, thanks to Laravel's Route Model Binding :

The form, using Form Model Binding :

Form::model($user, ['route' => ['user.setCredentials', $user->id]])

The route:

Route::post('credential/{user}', 'UsersController@setCredentials')->name('user.setCredentials');

On the controller:

public function setCredentials(User $user) {

  $this->user= $user;
}
    
answered by 05.08.2016 в 17:50