Laravel Static Model试图获取非对象的属性

I want to save my picture and all the logic is inside my Model. But my model is always return Trying to get a property of non object on line 80.

Here is my code:

In UserController.php:

DB::beginTransaction();
try{
    $user = new User($request->all());
    if($user->save()){
        User::savePicture($user->id, $request->cover);
    }
    DB::commit();
} catch(\Exception $e){
    DB::rollback();
}

In User.php (Model):

protected $picBaseDir = 'images/users/pic/';

public static function savePicture($id, UploadedFile $file)
{
    $user = static::find($id);

    $path = env('DIRECTORY') . $user->picBaseDir;
    makePath($path);

    // all other logic to move the image, etc
}

Line 80 is at $path = env('DIRECTORY') . $user->picBaseDir;

I've tried Log the id inside my model, it return correctly. But when I try log $user inside model it return empty.

Any solution?

Thanks


Found the solution. The culprit is my global scope inside user. It only check if the status is 1. When the user is saved, status is still 0.

Thanks.

Actually, I don't find problems with your code, but I think that there is no reasons to use static function. Let your users save its pictures by itself.

// UserController.php

$user = new User($request->all());
if($user->save()){
    $user->savePicture($request->cover);
}

// User.php
protected $picBaseDir = 'images/users/pic/';

public function savePicture(UploadedFile $file)
{
    $path = env('DIRECTORY') . $this->picBaseDir;
    makePath($path);

    // all other logic to move the image, etc
}
// UserController.php

$user = new User($request->all());
if($user->save()){
    User::savePicture($user->id, $request->cover);
}

// User.php
protected $picBaseDir = 'images/users/pic/';

public static function savePicture($id, UploadedFile $file)
{
    $user = User::find($id);

    $path = env('DIRECTORY') . $user->picBaseDir;
    makePath($path);

    // all other logic to move the image, etc
}