Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement named routes to controller with RESTful in Laravel 4?

I follow Laravel 4 tutorial at http://codebright.daylerees.com/.

at codebright.daylerees.com/controllers , you can see RESTful Controllers tutorial

I arrived at advanced routing tutorial codebright.daylerees.com/advanced-routing.

There is a sample code to use Route::get with named routes. Then I try to use Route::controller to make RESTful URI with named routes. Then, I try to write this code one routes.php:

Route::controller('my/very/long/article/route2', array(
'as'=>'article2',
'uses'=>'Blog\Controller\Article'
));

This is my controller/Article.php code:

<?php
namespace Blog\Controller;
use View;
use BaseController;

class Article extends BaseController
{
    public function getCreate()
    {
       return View::make('create');
    }
    public function postCreate()
    {

    }
}

When I try to access my/very/long/article/route2/create, it shows error

ErrorException
Array to string conversion
…\vendor\laravel\framework\src\Illuminate\Routing\Controllers\Inspector.php

Any idea how to implement named routes to controller with RESTful?

like image 870
Stephanus Budiwijaya Avatar asked Nov 19 '13 15:11

Stephanus Budiwijaya


1 Answers

The Route::controller method accepts three arguments. Third argument is optional and it's exactly what you need. Just pass the mapping of action names to named routes as third argument.

Code example:

Route::controller(
    'my/very/long/article/route2', 
    'Blog\Controller\Article',
    array(
        'getCreate' => 'article.create',
        'postCreate' => 'article.create.post' 
    )
);
// now you can use route('article.create.post') to get URL of Article::postCreate action
// and route('article.create') to get URL of Article::getCreate action

And yep, it looks little bit overcomplicated, but still better than separate routes for each action.

This solution is actual for Laravel 4.1 (not tested in other versions).

like image 52
Nayjest Avatar answered Oct 21 '22 04:10

Nayjest