如何在不使用 Laravel-Forms 的情况下将信息传递给 laravel5.7 中的 RESTful 控制器

How to pass information to a RESTful Controller in laravel5.7 without the use of Laravel-Forms

我正在尝试在 laravel 中设置一个简单的 CMS,可以在其中创建博客文章并将其保存在数据库中。我一直在关注使用资源控制器的 YouTube 教程,它运行良好。然而,教程系列使用 laravel-Forms 将参数传递给已弃用的控制器,因此我尝试用常规 html-Form 替换 laravel-Form 但我可以'让它工作。

我正在谈论的特定系列和其中的一部分是这个: https://www.youtube.com/watch?v=-QapNzUE4V0&index=7&list=PLillGF-RfqbYhQsN5WMXy6VsDMKGadrJ-

我将在下面粘贴包含我正在讨论的表单的 "create" 视图,然后我将其替换为无效的视图。

<h1>Create Post</h1>
{!! Form::open(['action' => 'PostsController@store', 'method' => 'POST', 'enctype' => 'multipart/form-data  ']) !!}
<form action="/posts" method="post" enctype="multipart/form-data">
    <div class="form-group">
        {{Form::label('title', 'Title')}}
        {{Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Title'])}}
    </div>
    <div class="form-group">
            {{Form::label('body', 'Body')}}
            {{Form::textarea('body', '', ['id' => 'article-ckeditor', 'class' => 'form-control', 'placeholder' => 'Body Text'])}}
    </div>
    {{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}

这是教程中的那个工作正常,它将所有参数从表单传递到控制器中的存储函数。 但是当我改用这种形式时:

<h1>Create Post</h1>
<form action="/posts" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <h1>Title<h1>
        <input type="text" class="form-control" name="title">
    </div>
    <div class="form-group">
            <h1>Body</h1>
            <textarea name="body" id="article-ckeditor" class="form-control" cols="30" rows="10"></textarea>
    </div>
    <input type="submit" value="Submit">
</form>

它将引导我到 /posts 并简单地说 "Error 419 - Your session has expired" 并且数据库中不会存储任何数据。

在这里你可以看到我在控制器中的存储功能:

public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required',
        'body' => 'required',
    ]);

    // Create Post
    $post = new Post;
    $post->title = $request->input('title');
    $post->body = $request->input('body');

    $post->save();

    return redirect('/posts')->with('success', 'Post Created');
}

感谢阅读!感谢您的帮助!

您将收到 419 错误,因为表单请求中不存在 CSRF 字段。 Laravel 表格包会自动为您添加此内容,但在标准 HTML 表格中,您必须自己添加。值得庆幸的是,这非常简单。在 <form> 块中,您只需添加 @csrf 例如

<h1>Create Post</h1>
<form action="/posts" method="post" enctype="multipart/form-data">

    @csrf

    <div class="form-group">
        <label>Title</label>
        <input type="text" class="form-control" name="title">
    </div>
    <div class="form-group">
        <label>Body</label>
        <textarea name="body" id="article-ckeditor" class="form-control" cols="30" rows="10"></textarea>
    </div>
    <input type="submit" value="Submit">
</form>

CSRF docs


任何使用 Laravel 5.5 或更低版本的人请注意,您需要使用 {{ csrf_field() }}@csrf

您现在可以导入 laravel collective,它是一个单独的包。我正在插入 link here.

对于像您这样的普通表单,您需要添加一个 csrf 字段。 Laravel collective 在这里有优势,因为它会自动添加这个字段,即使你没有声明它。 另外我更喜欢集体而不是传统形式。