Laravel不更新db记录(Model-> $存在false)

时间:2016-08-28 18:54:05

标签: php mysql laravel eloquent

我正在尝试更新我的"旅行名称" (name表中的user_trips字段。

我遵循了#34; Laravel From Scratch:更新记录和渴望加载"视频,但它没有更新,但我确实被重定向回来并获得会话msg"您的旅行已重命名"。我能看到的唯一区别是我使用的是一个页面(不是/编辑页面)。

问题是Laravels Model.php类中的$exists变量为false,因此它在false方法中返回update()

为什么$exists为假?

routes.php文件

<?php

Route::get('/', 'TripBuilderController@index');

Route::post('add_flight', 'FlightController@store');

Route::patch('trip/{trip}', 'TripBuilderController@update');

TripBuilderController

<?php
namespace App\Http\Controllers;

use App\Airport;
use App\UserTrips;
use Illuminate\Http\Request;

/**
 * Class TripBuilderController
 *
 * @package App\Http\Controllers
 */
class TripBuilderController extends Controller
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $airports=Airport::all();
        $user_trips=UserTrips::whereUserId(1)->with('userflights.flightfrom', 'userflights.flightto')->get();

        return view('welcome', compact('airports', 'user_trips'));
    }

    /**
     * @param Request $request
     * @param UserTrips $user_trips_obj
     */
    public function update(Request $request, UserTrips $user_trips_obj)
    {
        # Returns {"_token":"RANDOM TOKEN","_method":"PATCH","name":"New Trip Name"}
        //return $request->all();

        $user_trips_obj->update($request->all());
        # Returns []
        //return $user_trips_obj;

        # Results below.
        //dd($user_trips_obj);

        return back()->with('msg', 'Your trip has been renamed');
    }
}

UserTrips模型

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * Class UserTrips
 *
 */
class UserTrips extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps=FALSE;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable=[
        'name',
        'user_id'
    ];

    /**
     * @param UserFlights $user_flights_obj
     * @return Model
     */
    public function addFlight(UserFlights $user_flights_obj)
    {
        return $this->userflights()->save($user_flights_obj);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userflights()
    {
        return $this->hasMany(UserFlights::class);
    }

    /**
     * @return mixed
     */
    public function addTrip()
    {
        # Retrieve the trip by the attributes, or instantiate a new instance...
        $trip_obj=$this->firstOrNew(['user_id'=>1]);
        if(!$trip_obj->id)
        {
            $trip_obj->name='My Trip';
            $trip_obj->save();
        }

        return $trip_obj;
    }
}

welcome.blade.php

@extends('layouts.master')

@section('title', 'Trip Builder')

@section('content')
    <div id="airport_form">
        <form method="POST" action="/add_flight">
            {{ csrf_field() }}
            <div class="form-group">
                <select class="form-control" name="flight_from">
                    @foreach($airports as $airport)
                        <option value="{{ $airport->id }}">{{ $airport->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="form-group">
                <select class="form-control" name="flight_to">
                    @foreach($airports as $airport)
                        <option value="{{ $airport->id }}">{{ $airport->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">Add Flight</button>
            </div>
        </form>
    </div>
    <div id="trip_info">
        <div id="trip_form">
            <form method="POST" action="/trip/{{ $user_trips[0]->id }}">
                {{ csrf_field() }}
                {{ method_field('PATCH') }}
                <label for="trip_name">Trip Name:</label> <input type="text" name="name" id="trip_name" class="form-control" value="{{ $user_trips[0]->name }}"><button type="submit" class="btn btn-primary">Rename Trip</button>
            </form>
        </div>
        <div id="flight_info">
            <table class="table table-striped table-bordered table-hover">
                <tr>
                    <th>
                        From
                    </th>
                    <th>
                        To
                    </th>
                    <th>
                        Options
                    </th>
                </tr>
                @foreach($user_trips[0]->userflights as $user_flight)
                    <tr>
                        <td>
                            {{ $user_flight->flightfrom->name }}
                        </td>
                        <td>
                            {{ $user_flight->flightto->name }}
                        </td>
                        <td>
                            <a href="#">Remove</a>
                        </td>
                    </tr>
                @endforeach
            </table>
        </div>
    </div>
@stop

DD($ user_trips_obj);结果

UserTrips {#156 ▼
  +timestamps: false
  #fillable: array:2 [▼
    0 => "name"
    1 => "user_id"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  #attributes: []
  #original: []
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: false
  +wasRecentlyCreated: false
}

2 个答案:

答案 0 :(得分:2)

我看到的一个问题是Laravel的Route Model Binding将无法正常工作,因为您已在routes.php中命名模型trip。但是,在TripBuilderController类中,您已将其命名为$user_trips_obj。它应重命名为trip,否则您需要在routes.php中明确重新定义它。

所以,这个

public function update(Request $request, UserTrips $user_trips_obj)

应该是

public function update(Request $request, UserTrips $trip)

因为您已在routes.php

中将trip参数定义为trip

Route::patch('trip/{trip}', 'TripBuilderController@update');

请参阅Route Model Binding- Laravel Documentation

答案 1 :(得分:0)

请勿在您的请求中添加_token_method

$user_trips_obj->update($request->except(['_token', '_method']);

我的想法是,由于这些字段未被列入白名单,您在MassAssignemtnException上失败。

除此之外,请确保您的name作为模型中的可填充属性

protected $fillable = ['name'];