1

我希望有人能指出我将如何将下面的 Laravel 帖子从路由器移动到模型的正确方向?Laravel 文档使用路由解释了一切,但过了一段时间它就变成了一大堆代码。

Route::post('reminder', array('before' => 'csrf', function(){

    $rules = array(
        'first_name' => array('required', 'min:2'),
        'last_name' =>  array('required', 'min:2'),
        'email_address' =>  array('required', 'email')
        );

    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails()){
        return Redirect::to(Input::get('ref'))->withInput()->withErrors($validator);

    } else {

     DB::table('mytable')->insert(
        array(
        'fname' => Input::get('first_name'),
        'lname' => Input::get('last_name'),
        'email' => Input::get('email_address'),
    );
     return Redirect::to(Input::get('ref'))->with('message', 'Thank you.');     
    }
}));
4

2 回答 2

1

路线

Route::post('reminder', array('before' => 'csrf',
                              'as'=> 'reminder',
                              'uses' => 'HomeController@index',
                              ));

家庭控制器

public function index()
{
  $model = new HomeModel();
  $input = Input::all();
  $result = $model->insert($input);

  if($result instanceof \Illuminate\Validation\Validator)
  {
     return Redirect::to(Input::get('ref'))->withInput()->withErrors($result);
  } else {
     if($result)
     {
       return Redirect::to(Input::get('ref'))->with('message', 'Thank you.');
     } else {
      App::abort(500);
     }
  }
}

型号

public function insert($input)
{
  $rules = array(
    'first_name' => array('required', 'min:2'),
    'last_name' =>  array('required', 'min:2'),
    'email_address' =>  array('required', 'email')
    );

$validator = Validator::make($input, $rules);

if ($validator->fails()){
    return $validator;

} else {

 return DB::table('mytable')->insert(
    array(
    'fname' => $input['first_name'],
    'lname' => $input['last_name'],
    'email' => $input['email_address'],
);
}
于 2013-09-10T18:21:16.843 回答
-1

这实际上会进入您controllers目录中的控制器。

routes.php

Route::post('reminder', 'TestController@postReminder');

TestController.php

<?php 
class TestController extends BaseClass
{
    function postReminder()
    {
        $rules = array(
            'first_name' => array('required', 'min:2'),
            'last_name' =>  array('required', 'min:2'),
            'email_address' =>  array('required', 'email')
            );

        $validator = Validator::make(Input::all(), $rules);

        if ($validator->fails()){
            return Redirect::to(Input::get('ref'))->withInput()->withErrors($validator);

        } else {

         DB::table('mytable')->insert(
            array(
            'fname' => Input::get('first_name'),
            'lname' => Input::get('last_name'),
            'email' => Input::get('email_address'),
         );
         return Redirect::to(Input::get('ref'))->with('message', 'Thank you.');     
    }
    }
}
于 2013-09-10T18:22:02.610 回答