我想保存我的图片,所有的逻辑都在我的模型中。但我的型号总是返回Trying to get a property of non object on line 80.
这是我的代码:
在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();
}
在User.php(型号)中:
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
}
80号线位于$path = env('DIRECTORY') . $user->picBaseDir;
我已经尝试在我的模型中记录id,它返回正确。但当我尝试在模型中记录$user
时,它返回为空。
有什么解决方案吗?
感谢
找到了解决方案。罪魁祸首是我在用户内部的全局范围。它只检查状态是否为1。保存用户后,状态仍然为0。
谢谢。
实际上,我没有发现您的代码有问题,但我认为没有理由使用静态函数。让您的用户自己保存图片。
// 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
}