首页 > 解决方案 > 无法在 Laravel 中使用 findOrFail 方法更新

问题描述

我是 Laravel 的新手。所以我试图更新我的表单,但它一直返回失败,因为我使用findOrFail了控制器上的方法。

但是当我试图转储时IdId确实存在。

只有当我使用该方法调用它时,它才会返回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;
    }

很高兴你们中的任何人注意到什么,谢谢。

标签: phplaravel

解决方案


您可以在 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.

}

推荐阅读