What I'm looking for here, is an elegant way of creating a new Contact. As the image says, a Contact must have a "client_id".
Basically, my Client detail view has a link that's labelled "Add Contact". To my mind, it makes sense if this links to the ContactsController's create-method. That's where the first issue arises; the route for create, doesn't take a parameter by default, and I need the parent Client's id.
So, I edit my routes.php-file, exclude "create" from the resource-route and roll my own route for the create-method. Looks like this:
Route::resource('contacts', 'ContactsController', array('except' => array('create', 'index', 'show')));
Route::get('contacts/{clients}/create', array('as' => 'contacts.create', 'uses' => 'ContactsController@create'));
Next I have to add a hidden form-input to the create-method's view and give it a name of "client_id". Then I have to make client_id fillable in the Contact-model. I also have to add client_id as 'required' in the validation rules.
I'm using Laracasts's validation-package found here, meaning I have a separate class that's responsible for the validation of Contacts. This is where I have to tell Laravel that "client_id" is required. Subsequently, I now have to add client_id as a hidden form-input to my contact update-view as well (since the same validation is run on create- and update-methods).
This, to me, seems like a lot of workarounds for a relatively simple problem. I was just wondering if some of you guys knew of simpler ways to achieve this without abandoning resourceful concepts completely.
Thanks!
Should someone else come across this, the answer is "nested resources". In my case, I solved it by doing this:
Route::resource('clients.contacts', 'ContactsController', array('except' => array('create', 'index', 'show')));
A simple php artisan routes-call reveals that the routes created for the ContactsController should contain two parameters in the url, one client id and one contact id (where applicable). Handling contacts is now a cinch in the controller and can be done in the proper RESTful way.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community