【问题标题】:How do I deal with controller resource in laravel如何处理 laravel 中的控制器资源
【发布时间】:2020-02-12 17:22:03
【问题描述】:

我正在为我的控制器和路由使用资源工具,但 store 方法似乎不起作用。你能强调一下我做错了什么吗?控制器名称是否需要与型号一相同?我很困惑

农场控制器

<?php

namespace App\Http\Controllers;

use App\Animal;
use Auth;
use Illuminate\Http\Request;

class FarmController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function __construct()
    {
        $this->middleware('auth');
    }


    public function index()
    {
        $animal = Animal::all();
        return view('farms.index', compact('animal'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = Auth::user();
        $animal = new Animal();
        return view('farms.create', compact('user', 'animal'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        Animal::create($this->validateRequest());


        return redirect('farms.show');
    }
    private function validateRequest()
    {
        return request()->validate([
            'dateOfBirth' => 'required|date',
            'placeOfBirth' => 'required',
            'gender' => 'required',
            'user_id' => 'required',
        ]);
    }

Animal.php(控制器)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Animal extends Model
{
    protected $guarded = [];
    public function user(){
        return $this->belongsTo(User::class);
    }}

animals (table)

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAnimalsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('animals', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id')->index();
            $table->date('dateOfBirth');
            $table->string('gender');
            $table->string('placeOfBirth');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('animals');
    }
}

create.blade.php

@extends('layouts.app')
@section('title', 'Add Animal')
@section('content')
    <div class="row">
        <div class="col-12">
            <h1>Farm</h1>
        </div>
    </div>
    <h3>Welcome {{ $user->name }} Please Add an animal</h3>
    <div class="row">
        <div class="col-12">
            <form action="{{ url('farms') }}" method="POST">
                <div class="form-group">
                    <label for="dateOfBirth">Date Of Birth: </label>
                    <input type="date" name="dateOfBirth" class="form-control" placeholder="dd/mm/yyyy">
                </div>
                <div class="pb-5">
                    {{ $errors->first('dateOfBirth') }}
                </div>
                <div class="form-group">
                    <label for="placeOfBirth">Place Of Birth</label>
                    <input type="text" name="placeOfBirth" class="form-control">
                </div>
                <div class="pb-5">
                    {{ $errors->first('placeOfBirth') }}
                </div>
                <div class="form-group">
                    <label for="gender">Gender: </label>
                    <select name="gender" class="form-control">
                        <option value="M">Male</option>
                        <option value="F">Female</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="user">User</label>
                    <select class="form-control" name="user">
                        <option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary">Add Farm</button>

                @csrf
            </form>
        </div>
    </div>
@endsection

web.php(路由)

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::middleware('admin')->group(function () {

    // All your admin routes go here.

    Route::resource('/admin', 'AdminController');
});

Route::middleware('farms')->group(function () {

    // All your admin routes go here.
    Route::resource('/farms', 'FarmController');
});

当我提交表单时,它似乎只是刷新了页面,并没有在我的表格中添加任何内容。我整整两天都被困在这个问题上。欢迎任何帮助

【问题讨论】:

    标签: laravel


    【解决方案1】:

    在您拥有的validateRequest 函数中

    'user_id' => 'required',
    

    但是视图中的表单没有名为user_id的字段

    选择元素被命名为user

    <select class="form-control" name="user">
      <option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
    </select>
    

    换一个让他们可以匹配,我猜是页面刷新只是验证失败

    您可能需要检查视图中的 any 验证错误,以找出问题所在 the docs

    例如

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      只需更改您的表单操作,然后它就会以正确的方法命中。这是您的表单的操作

      {{route('farms.store')}}
      

      【讨论】:

        猜你喜欢
        • 2016-12-22
        • 1970-01-01
        • 1970-01-01
        • 2014-05-29
        • 1970-01-01
        • 2019-10-02
        • 1970-01-01
        • 2020-12-09
        • 2017-12-18
        相关资源
        最近更新 更多