dsc6517 2014-05-24 01: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-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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失