收藏功能报错找不到原因
我照着教程5改写了一个收藏功能,但是一直提示我'test_psy_id' cannot be null
,相关的modal的fillable
我都设置了,但是都不行,以下是代码:
route:
Route::post('/testpsies/{product}/favorite', 'TestPsiesController@favor')->name('testpsies.favor');
Route::delete('/testpsies/{product}/favorite', 'TestPsiesController@disfavor')->name('testpsies.disfavor');
controller
//测试题收藏
public function favor(TestPsy $test_psy, Request $request)
{
$user = $request->user();
if ($user->favTests()->find($test_psy->id)) {
return [];
}
$user->favTests()->attach($test_psy);
return [];
}
//取消收藏
public function disfavor(TestPsy $test_psy, Request $request)
{
$user = $request->user();
$user->favTests()->detach($test_psy);
return [];
}
modal
public function favTests()
{
return $this->belongsToMany(TestPsy::class, 'user_test_favs')
->withTimestamps()
->orderBy('user_test_favs.created_at', 'desc');
}
blade
//添加收藏
$('.btn-favor').click(function() {
$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
$.ajax({
url: "{{ route('testpsies.favor', [$testpsy]) }}",
type: "POST",
data: {
"test_psy_id": {{ $testpsy->id }}
},
complete:function(error) { // 请求失败会执行这个回调
// 如果返回码是 401 代表没登录
if (error['status'] === 401) {
window.location.href = "{{ route('users.index') }}";
}
},
success:function(data){
console.log('操作成功');
}
}
})
});
找到原因了,隐形路由的参数要一致