Updating Multiple Models in a single Form, how to improve?
Hi,
I was writing code to update multiple models (4 students) in a form. I did something like this:
<textarea name="description-{{$student->id}}"
id="description-{{$student->id}}"
placeholder="You may use markdown for this field">
</textarea>
Then in my controller, I do a split to find out the description field is for which student as a student of id 1 will be description-1.
It works but somehow I felt that it could be better handled. If you are wondering, the reason why my page edit 4 students at once is a client requirement. Each class has 4 students and they do not want to go separate pages to edit their information.
Wow @pmall, thanks for the tip, this is something I didn't know about previously.
Then to the question of validation.
Because the validation are repeated for each model, is there a elegant way to duplicate the validations in the models/controller and display it on frontend?
Update: I'm using Laravel 4.2 with laravel validating package.
We use dependency injection to make sure that the right request object is used. The create function will automatically use the rules in the StudentRequest class
StudentController.php
public function store(StudentRequest $request)
{
Student::create($request->all());
}
Now we need to create the students request class (You can generate it with php artisan make:request StudentRequest)
StudentRequest.php
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class StudentRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true; // The user is always permitted to do this, so we perform no action here
}
/**
* Get the validation rules that apply to the student request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|min:3',
'description' => 'required'
];
}
}
@polarcubs no other solution than constructing an array of rules somehow, according to the number of students in the request input. Then use dot notation :