dsc6517 2014-05-24 01:56
浏览 56
已采纳

如何在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-24 02: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.

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置