duandang6111
2019-04-13 19:30
浏览 255
已采纳

如何将表单数据提交到MySQL数据库

I am relatively new to Laravel and coding in general. I am trying to use Eloquent and to pass data from my form into a MySQL database. I can "submit" without any errors but don't see the data in the table. I feel like my code is getting messier as I am trying to figure this out and I would love a review of my code. I've tried several different ways of doing this by reading through tutorials, books and reviewing other people's code.

Route

Route::post('submit', function (Request $request) {
    $data = $request->validate([
        'title' => 'required|max:255',
        'category' => 'required|max:255',
        'content' => 'required|max:900',
    ]);
    return redirect('submit');
});

Controller

<?php

public function store(Request $request)
{
    Post::create([
        'title' => $request->title,
        'category' => $request->category,
        'content' => $request->content,
    ]);

    return redirect('views.submit');
}

View/Blade

<div>
    <form action='' method='post'>
        @csrf
        <p><label>Title</label><br/>
            <input type='text' name='title' value=''><?php if (isset($error)) {
                echo $_POST['title'];
            }?></p>
        <p><label>Category</label><br/>
            <textarea name='category' cols='60' rows='10'><?php if (isset($error)) {
                    echo $_POST['category'];
                }?></textarea></p>
        <p><label>Content</label><br/>
            <textarea name='content' cols='60' rows='10'><?php if (isset($error)) {
                    echo $_POST['content'];
                }?></textarea></p>
        <p><input type='submit' name='submit' value='Submit'></p>
    </form>
</div>

I'm expecting this to pass data to my table named "blogs."

1条回答 默认 最新

相关推荐 更多相似问题