Brian Dillingham Brian Dillingham - 1 year ago 109
PHP Question

Laravel nested resource route parameters in html forms & urls

Im essentially trying to see if there is a more efficient or proper way of accessing route parameters in the views of a nested resource. The code below demonstrates what I'm doing, catching all parameters from the route:


into the controller index method, and then making a view and passing it all of those parameters so that within the view I can make forms and links that use the same route format & parameters. Is there a better way? Laravel Paste

// app/routes.php

Route::resource('schools.classes.teachers.assignments', 'AssignmentsController');

// app/controllers/AssignmentsController.php

public function index($school_id,$class_id,$teacher_id)
$routes = array($school_id,$class_id,$teacher_id);
$assignments = $this->assignment->all();

return View::make('assignments.index', compact('assignments'))
->with('routes', $routes);

// app/views/assignments/index.blade.php
// ------------------------------------------------------------

<p>{{ link_to_route('schools.classes.teachers.assignments.index', 'All Assignments', array($routes[0],$routes[1],$routes[2])) }}</p>

// app/views/assignments/edit.blade.php
// -------------------------------------------------------------

{{ Form::model($assignment, array('method' => 'PATCH', 'route' => 'schools.classes.teachers.assignments.update', $routes[0],$routes[1],$routes[2],$route[3]))) }}


Answer Source

You always need to pass the parameters and this is simple but I think it would be better if you use an associative array like this instead:

$routes = compact('school_id', 'class_id', 'teacher_id');

So it'll become:

$routes = array(
    'school_id' => $school_id,
    'class_id' => $class_id,
    'teacher_id' => $teacher_id

So, you can use:

{{ Form::model($assignment, array('method' => 'PATCH', 'route' => 'schools.classes.teachers.assignments.update', $routes['school_id'], ['class_id'], ['teacher_id']))) }}

Looks more readable and easy to understand.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download