dsc6517 2014-05-23 17:56
浏览 57
已采纳

如何在laravel 4.1中将模型作为参数传递?

So, maybe i'm not connecting the dots very well, between my models. I get the error:

Argument 1 passed to RespuestaController::postRespuesta() must be an instance of Question, string given

when i pass the Question model in my view:

{{ Form::open( array( 'action' => array( 'RespuestaController@postRespuesta', $question->id ) ) )  }}

Here's my app/routes.php:

Route::model('respuesta', 'Respuesta');
Route::model('question', 'Question');

Route::resource('questions', 'QuestionController');
Route::controller('respuestas', 'RespuestaController');

and the RespuestaController:

class RespuestaController extends \BaseController {

public function postRespuesta(Question $question)
{
    $validator = Validator::make(Input::all(),
        array(
            'respuesta' => 'required'
        )
    );

    if( $validator->fails() ){
        return Redirect::route('questions.show')
            ->withErrors($validator);
    }else{
        $respuesta = Input::get('respuesta');

        $respuesta = Respuesta::create(array(
                        'respuesta' => $respuesta
                    )
        );

        $respuesta->save();
        $question->respuesta()->associate($respuesta)->save();
        $respuesta->user()->associate(Auth::user())->save();

//$question = Question::find($question); //this works without (Question $question), but i think is not a good practice or is it??


    }


}

}

Am i doing the model binding right?? Or is just for routes created manually instead of only Route::controller('respuestas', 'RespuestasController');

Thanx for your support.

展开全部

  • 写回答

1条回答 默认 最新

  • dongquanlin1885 2014-05-23 18:20
    关注

    You need to bind the resource name as the same name as the model resource (not the model name) - so try this:

    Route::model('questions', 'Question');   
    Route::resource('questions', 'QuestionController');
    

    Note - you cannot use this on a Route::controller().

    Personally I suggest not using either resource() or controller() - but instead manually define all your routes. This is a link to a great blog post by Phil Sturgeon on why you should consider manually defining all your routes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部