小编Osv*_*vyG的帖子

Laravel 5 mutators仅在我创建记录时工作,而不是在我更新记录时

嗨,我已经创建了一个mutator,只在我的电话号码上存储数字.这是我的个人资料模型中的代码.

public function setPhoneAttribute($phone)
{
    $this->attributes['phone'] = preg_replace("/[^0-9]/","",$phone);
}
Run Code Online (Sandbox Code Playgroud)

这在我创建新记录时有效,但如果我更新记录则不起作用.我的问题是如何在创建和更新上执行Mutator?

以下是我在控制器中更新和创建的方法:

namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Requests\ProfileRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Profile;

class ProfileController extends Controller {

    public function create(ProfileRequest $request)
    {
        // Check if the user does not have a profile yet
        if(!Auth::user()->profile()->first()){

            // Save to database
            $saveToDatabase = Auth::user()->profile()->create($request->all()); 

            return $saveToDatabase;
        }
    }

    public function update(Profile $profile, ProfileRequest $request)
    {

        // Save to database
        $saveToDatabase = Auth::user()->profile()->update($request->all());

        return $saveToDatabase;
    }
}
Run Code Online (Sandbox Code Playgroud)

php mutators laravel laravel-5

11
推荐指数
1
解决办法
4421
查看次数

标签 统计

laravel ×1

laravel-5 ×1

mutators ×1

php ×1