php - 无法在 Laravel 中使用 findOrFail 方法更新
问题描述
我是 Laravel 的新手。所以我试图更新我的表单,但它一直返回失败,因为我使用findOrFail
了控制器上的方法。
但是当我试图转储时Id
,Id
确实存在。
只有当我使用该方法调用它时,它才会返回null
.
更新路线
Route::post('/alumni/updateProfile','AlumniController@update');
更新方法
public function update(Request $request, User $user, Profile $profile)
{
$user->roles()->sync($request->roles);
$profile = Profile::findOrFail(Auth::user()->id);
$profile->name = $request->name;
$profile->matric_no = $request->matric_no;
$profile->contact_no = $request->contact_no;
$profile->address = $request->address;
$profile->batch_year = $request->batch_year;
$profile->graduation_year = $request->graduation_year;
$profile->date_of_birth = $request->date_of_birth;
$profile->area_of_interest = $request->area_of_interest;
$profile->start_date = $request->start_date;
$profile->company_name = $request->company_name;
$profile->job_title = $request->job_title;
$profile->social_network = $request->social_network;
$profile->save();
return view('/home', compact('profile'));
}
轮廓模型
class Profile extends Model
{
// protected $guarded = [];
protected $fillable = ['alumni_id'];
protected $table = 'profiles';
public $timestamps = false;
public function users()
{
return $this->belongsTo('App\User');
}
}
用户模型
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function profiles()
{
return $this->belongsTo('App\Profile');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
很高兴你们中的任何人注意到什么,谢谢。
解决方案
您可以在 try catch 博客中编写 findOrFail() 并在 catch 博客中获取异常以了解错误。
或者
您可以编写下面的代码而不是 findOrFail()。
$profile = Profile::where('id', '=', Auth::user()->id);
if( $profile->count() ){
# Assignment of values to database columns fields and then save.
$profile->save();
} else {
# Print No Record Found.
}
推荐阅读
- javascript - 在 React 中,使用引导模式如何编辑和更新状态?
- c++ - c++ 中的堆栈实现,没有最大堆栈大小限制
- python - 将原始日期格式转换为 pandas 日期对象
- mongodb - 在 Ubuntu Snap 安装上更改默认 MongoDB 端口
- python - conv_lstm.py 示例使用 'binary_crossentropy' 损失进行回归。为什么不使用“mean_squared_error”呢?
- database - 将自定义 Wordpress 联系表单数据存储到联系表单数据库中
- reactjs - React 路由不起作用
- python - 欧几里得除法定理程序
- reactjs - ReactJS 的最小构建块是什么 - 元素或组件?
- c# - 如何从 TextBox 获取值并自动应用格式?