【问题标题】:Laravel Not Accessing The Request of data postLaravel 未访问数据发布请求
【发布时间】:2017-06-22 14:16:38
【问题描述】:

这里我在 Laravel 中创建了一个表单,通过路由“posts.store”将请求发布到控制器“PostsController”

        {!! Form::open(['url' => 'posts.store']) !!}
            {{Form::Label('title','Title:')}}
            {{Form::Text('title',null,array('class' => 'form-control'))}}
            {{Form::Label('body','Post Body:')}}
            {{Form::Textarea('body',null,array('class' => 'form-control'))}}
            {{Form::Submit('Create Post',array('class' => 'btn btn-success btn-lg btn-block','style' => 'margin-top:20px;'))}}
        {!! Form::close() !!}

这是我试图通过错误访问我的请求的“PostsController”:

public function store(Request $request)
    {
        //validate data
        $this-> validate($request, array(
            'title' => 'required|max:255',
            'body'  => 'required'

            ));
        //Store data into database
        $post = new Post;

        $post->title = $request->title;
        $post->body = $request->body;
        $post->save();

        return redirect()->route('posts.show', $post->id);
    }

当我提交表单时,会出现以下页面

NotFoundHttpException:

【问题讨论】:

  • 你的路线有什么可以告诉我们

标签: php laravel-5


【解决方案1】:

改变这个:

{!! Form::open(['url' => 'posts.store']) !!}

到这里:

{!! Form::open(['url' => 'PostController@store']) !!}

要获取 PostData,你需要这个:

$postData = $this->request->all();
$post->title = $postData['title'];
$post->body = $postData['body'];

【讨论】:

  • 应用这两项更改后,仍然在 RouteCollection->methodNotAllowed(array('GET', 'HEAD', 'PUT', 'PATCH', 'DELETE ')) 在 RouteCollection.php 中(第 238 行)
  • 你需要在路由中添加方法 POST
  • 我使用了这个 Route::resource('posts','PostsController');因为我必须把所有的资源都用起来
  • 仍然无法正常工作,但是当我尝试像这样分隔我的路线时 Route::post('posts/store','PostsController@store'); Route::get('posts/show','PostsController@show');然后数据被插入到数据库中,重定向错误 return redirect()->route('posts.show', $post->id);错误:未定义路由“posts.show”
【解决方案2】:

在您的 NotFoundException 屏幕截图中,您可以看到它要访问的 URL 是 http://127.0.0.1:8000/posts.store 显然这是行不通的。将{!! Form::open(['url' => 'posts.store']) !!} 更改为Form::open(['action' => 'PostsController@store', 'method' => 'POST'])。此外,请确保您的 POST 路由已在 web.php 中设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    相关资源
    最近更新 更多