【发布时间】:2020-06-11 15:38:00
【问题描述】:
我遇到了奇怪的问题。资源方法总是返回 null。
表名
operating_days
型号
class OperatingDay extends Model
{
/**
* @var string[]
*/
protected $fillable = ['day', 'date'];
}
控制器@edit
public function edit(OperatingDay $operatingDay)
{
return view('admin.day.form')->with('operatingDay', $operatingDay)->with('title', __('admin.day.edit_day'));
}
路线
Route::resource('days', 'OperatingDayController')->names([
'index' => 'admin.days.index',
'store' => 'admin.days.store',
'create' => 'admin.days.create',
'show' => 'admin.days.show',
'update' => 'admin.days.update',
'destroy' => 'admin.days.destroy',
'edit' => 'admin.days.edit',
]);
在视图中添加 var
@dd($operatingDay)
App\OperatingDay {#1400 ▼
#fillable: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
@dd($operatingDay->id)
// output null
【问题讨论】:
-
我认为问题在于您将资源命名为
days,因此 Laravel 试图将其路由到名为Day的模型,但您的模型名为OperatingDay。您能否尝试将以下内容添加到您的 RouteServiceProvider 的启动方法中:Route::model('day', OperatingDay::class);并检查它是否有效。 -
完美,非常感谢。解决。 :)
-
我添加了一个带有文档链接的答案。