数据保存或更新时,Laravel返回null

时间:2016-10-05 07:45:30

标签: php laravel

我多次使用此代码部分没有问题。但这次$ success返回null并且我无法理解。当我检查数据库时,我看到用户1已更新。由于它节省了,因此没有可填写的问题。我也尝试了save()函数。我错过了什么?感谢帮助。

(Laravel版本5.2.45)

$user = User::find(1);
$user->firstname = $request->firstname;
$user->lastname = $request->lastname;
$success= $user->update(); // Database update is successful
dd($success); // But return null

用户模型

<?php
namespace App;

use App\Presenters\UserPresenter;
use App\Services\Logging\UserActivity\Activity;
use App\Support\Authorization\AuthorizationUserTrait;
use App\Support\Enum\UserStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
use CanResetPassword, AuthorizationUserTrait;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

protected $dates = ['last_login', 'birthday'];
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $guarded = [];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password', 'remember_token'];

public function items()
{
    return $this->hasMany('App\Item');
}
/**
 * Always encrypt password when it is updated.
 *
 * @param $value
 * @return string
 */
public function setPasswordAttribute($value)
{
    $this->attributes['password'] = bcrypt($value);
}

public function gravatar()
{
    $hash = hash('md5', strtolower(trim($this->attributes['email'])));

    return sprintf("//www.gravatar.com/avatar/%s", $hash);
}

public function isUnconfirmed()
{
    return $this->status == UserStatus::UNCONFIRMED;
}

public function isActive()
{
    return $this->status == UserStatus::ACTIVE;
}

public function isBanned()
{
    return $this->status == UserStatus::BANNED;
}

public function city()
{
    return $this->belongsTo(City::class, 'city_id');
}
public function activities()
{
    return $this->hasMany(Activity::class, 'user_id');
}
public function getRememberToken()
{
    return $this->remember_token;
}

public function setRememberToken($value)
{
    $this->remember_token = $value;
}

public function getRememberTokenName()
{
    return 'remember_token';
}
public function getAuthIdentifier()
{
    return $this->getKey();
}

public function getAuthpassword()
{
    return $this->password;
}

public function getAuthIdentifierName()
{
    return $this->getKeyName();
}
public function verification()
{
    return $this->hasOne('App\Verification');
}
}

更新问题(新尝试):

我尝试使用更新功能的空控制器。我仍然失败了。

UserController.php

<?php

namespace App\Http\Controllers;

use App\User;
use Auth;
use Illuminate\Http\Request;

class UserController extends Controller
{

public function getEdit()
{
    $user = User::find(1);
    return view('user.editprofile', compact('user'));
}

public function postEdit(Request $request)
{
    $user = User::find(1);
    $user->firstname = $request->firstname;
    $user->lastname = $request->lastname;
    if($user->update())
    {
        echo "Success";
    }
    echo "Fail"; // Print "Fail" but update was successful.
}

}

4 个答案:

答案 0 :(得分:1)

成功插入或更新记录后,laravel会在成功时返回true,在失败时返回false,您也可以这样检查。

 if($user->save()){
     //do something when user is save 
 }else{
     // do something wehn user is not update
 }

if($user->update()){
     //do something when user is update 
 }else{
     // do something wehn user is not update
 }

答案 1 :(得分:0)

我通常这样做是为了确保成功保存

try {
    DB::beginTransaction();
    // save or update happen in here
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    // something happen in here when error
}

代表

DB::beginTransaction();
DB::commit();
DB::rollback();

是可选的,但我推荐它,因为当中间发生任何不良事件时,它会为您回滚保存的数据。

答案 2 :(得分:0)

尝试使用数组更新用户。喜欢这个

$user = User::find(1);
$dataToUpdate['firstname'] = $request->firstname;
$dataToUpdate['lastname'] = $request->lastname;
if($user->update($dataToUpdate))
{
    echo "Success";
}
echo "Fail"; // Print "Fail" but update was successful.

您也可以尝试添加:

protected $fillable = ['firstname', 'lastname'];

到您的User.php模型

答案 3 :(得分:0)

我发现了问题。有一个特征覆盖保​​存和更新功能。

use App\Support\Authorization\AuthorizationUserTrait