laravel-5.4 - error :Creating default object from empty value

ぐ巨炮叔叔 提交于 2019-12-06 00:44:50

问题


I want to store image path in database. My Controller code undervendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php follows:

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    if($request->hasFile('image')) {
    $image_name = $request->file('image')->getClientOriginalName();              
    $image_path = $request->file('image')->store('public'); 
    $user->image = Storage::url($image_name);
    $user->save();
    }

    event(new Registered($user = $this->create($request->all())));

   // $this->guard()->login($user); disable autologin for new users

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

I am getting the following error: ErrorException in RegistersUsers.php line 40: Creating default object from empty value .

The image is getting saved in public folder but not able to save image path in the user table database. schema of user table
Schema::create('users', function (Blueprint $table) { $table->increments('user_id'); $table->string('name'); $table->string('image'); $table->rememberToken(); $table->timestamps();

how to proceed to store the image path in the user table in database


回答1:


you haven't initialized the variable $user so in the controller and before using it you've to add $user = new User; assuming that you already have use App\User;

or $user = new \App\User; if you don't.

Update if you're trying to update an existing user record you've to initialize the $user variable by selecting based on it's primary key which should be sent in the request and then doing the initialization like:

$user_id = $request->input('user_id');
$user = User::find($user_id);



回答2:


Use the simple way below:

$user = User::where('id', '=', $id)->first(); // where id is method param from url or request object
$user->save();

This is also easier when updating multiple tables where the ids in the sub-tables have foreign keys and need to be explicitly defined in the update process.

Also $user = User::find($id); normally work where the $id is the primary key of that object table



来源:https://stackoverflow.com/questions/43488754/laravel-5-4-error-creating-default-object-from-empty-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!