将数据从下拉列表推送到Laravel中的数据库

时间:2018-08-07 19:39:09

标签: php laravel

我在使用Laravel向MySQL添加数据时遇到问题。 假设我们有一个带有“类别”列的表格“书”,也假设用户只能选择3个类别。因此,我们有一个带有“恐怖,恐怖,动作”的下拉列表,当我们想添加一本新书时,我们必须提供其书名,并从下拉列表中选择一个类别。 我写道:

create.blade.php
            <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
                <label>Book title</label>
                <input type="text" class="form-control" name="name" placeholder="The title of the book" value="{{ old('title') ? : $books->title }}">
            <div class="form-group{{ $errors->has('category_id') ? ' has-error' : '' }}">
                <label>Category</label>
                <select class="form-control" name="category_id">
                        <option value="{{ old('name') ? : $books->category_id }}">Horror</option>
                        <option value="{{ old('name') ? : $books->category_id }}">Action</option>
                        <option value="{{ old('name') ? : $books->category_id }}">Thriller</option>

                </select>
            </div>

但是我得到一个错误:/

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_id' cannot be null (SQL: insert into `books` (`category_id`, `title`, `updated_at`, `created_at`) values (, , 2018-08-07 19:37:28, 2018-08-07 19:37:28))

我也是PHP和Laravel的新手,因此请为每个解决方案提供简短说明。谢谢!

BooksRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BooksRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
        ];
    }
}

BooksController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Books;
use App\Http\Controllers\Controller;
use App\Services\TranslationService;
use App\Translation;
use Illuminate\Http\Request;
use App\Http\Requests\BooksRequest;

class BooksController extends Controller
{
    public function index()
    {
        $books = books::all();
        return view('books.index', compact('books'));
    }
    public function create()
    {
        $books = new Books();
        return view('books.create', compact('books'));
    }
    public function store(BooksRequest $request)
    {
        $books = new Books();
        $books ->title = $request->title;
        $books ->category_id= $request->category_id;

        if($books ->save()) {
            return redirect()->route('books.index')->with(['success' => true, 'message_type' => 'success', 'message' => 'Success '.$request->title.'.']);
        }
        return back()->with(['success' => false, 'message_type' => 'danger', 'message' => 'Bad'.$request->title.'. Try later.']);
    }
}

1 个答案:

答案 0 :(得分:0)

我将Input(„ valuename“)与请求一起使用,并且可以正常工作:) https://laravel.com/docs/5.6/requests