【问题标题】:Getting only data for specified HTTP method?仅获取指定 HTTP 方法的数据?
【发布时间】:2013-07-02 10:28:35
【问题描述】:

我现在只是在玩 Laravel,试图确定它是否是用于项目的一个不错的框架选择。

我已经从here 下载了生成器包,并按照文档创建了一个资源。

这给了我一个带有作者和正文的表格。

生成的 store 方法如下所示:

/**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $input = Input::all();
        $validation = Validator::make($input, Tweet::$rules);

    if ($validation->passes())
    {
        $this->tweet->create($input);

        return Redirect::route('tweets.index');
    }

    return Redirect::route('tweets.create')
        ->withInput()
        ->withErrors($validation)
        ->with('message', 'There were validation errors.');
}

它似乎工作正常,除了 $input 数组包含 $_GET 变量以及 $_POST。它验证 OK,但在尝试保存模型时会导致异常,因为它包含意外字段(来自 $_GET 超全局的任何内容都会添加到查询中)。

SQLSTATE[42S22]:未找到列:1054 中的未知列“推文” '字段列表' (SQL: 插入tweets (author, body, tweets, updated_at, created_at) 值 (?, ?, ?, ?, ?)) (绑定: 数组 ( 0 => 'zzz', 1 => 'zzzzz', 2 => '', 3 => '2013-07-02 10:23:16', 4 => '2013-07-02 10:23:16',))

有没有办法只传递相关值,或者我必须手动删除我不想使用的任何东西?

任何建议表示赞赏。

谢谢

【问题讨论】:

    标签: php laravel laravel-4 crud


    【解决方案1】:
    You can pass selective input variables to the withInput() method.
    
    This is how your code would look like:
    
    return Redirect::route('tweets.create')
            ->withInput(Input::except('tweets'))
            ->withErrors($validation)
            ->with('message', 'There were validation errors.');
    
    
    also you can use to pass "selective inputs" or remove "selective inputs from all input vars". Here is the code you can use:-
    
    
    $input = Input::only('username', 'password');  // selective inputs
    
    $input = Input::except('tweets'); // remove selective inputs
    

    【讨论】:

      【解决方案2】:

      据我所知,目前在 Laravel 4 中没有办法只使用 Input::all(); 方法检索 $_GET 或 $_POST 输入,但有 Input::only()Input::except() 方法如果您不知道,请按照他们在锡上说的做...

      只需向他们传递您要包含在字符串中的键的数组

      $input = Input::only('author', 'body','tweets');
      

      或要排除的键数组

      $input = Input::except('updated_at');
      

      它只会检索您指定的值(或您未排除的值)。我知道这并不像某种 Input::all('post'); 函数那么简单,但这是不改变你自己的 Laravel 的唯一方法。我个人认为这可能是对框架的一个很好的补充

      【讨论】:

        【解决方案3】:

        在 Laravel 4 中获取 POST(PUT 等)变量的最简单方法如下:

        $post = Input::duplicate(array())->all();

        这意味着:获取当前请求,克隆它,并将 $_GET 参数替换为空数组。

        您可能需要进一步调查 duplicate() 以了解如何避免进一步与 cookie 等发生冲突。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-06
          • 2017-04-28
          • 2012-11-25
          • 2020-11-23
          • 1970-01-01
          • 2014-04-05
          相关资源
          最近更新 更多