Last active
January 10, 2020 00:38
-
-
Save robsonsuzin/a7cf6c0d6f6fccd25ff0014793337171 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Upload photo the specified resource in storage. | |
| * | |
| * @param UploadUser $request | |
| * @param User $user | |
| * @return Response | |
| */ | |
| public function uploadPhoto(UploadUser $request, User $user) | |
| { | |
| // Define um aleatório para o arquivo baseado no timestamps atual | |
| $name = Str::slug($user->name, '-') . '-' . uniqid(date('HisYmd')); | |
| // Recupera a extensão do arquivo | |
| $extension = $request->photo->extension(); | |
| // Define finalmente o nome | |
| $nameFile = "{$name}.{$extension}"; | |
| // Faz o upload: | |
| $upload = $request->photo->storeAs('public/users', $nameFile); | |
| // Salva a thumbnail | |
| $destinationPath = storage_path("app/public/users/thumbnail"); | |
| $img = Image::make(storage_path("app/public/users/{$nameFile}")); | |
| $img->resize(600, 600, function ($constraint) { | |
| $constraint->aspectRatio(); | |
| })->save("{$destinationPath}/{$name}-600-{$extension}"); | |
| // Verifica se NÃO deu certo o upload | |
| if (!$upload) { | |
| return response()->json([ | |
| 'errors' => [ | |
| 'message' => 'Não foi possível fazer o upload da foto!' | |
| ], | |
| ], 400); | |
| } | |
| if ($user->photo !== null){ | |
| // Remove a foto antiga | |
| Storage::disk('public')->delete('/users/'.$user->photo); | |
| // Remove a foto antiga do thumbnail | |
| $thumbnail = explode('.', $user->photo); | |
| Storage::disk('public')->delete("/users/thumbnail/{$thumbnail[0]}-600-{$thumbnail[1]}"); | |
| } | |
| $user->photo = $nameFile; | |
| $user->save(); | |
| return response()->json([ | |
| 'data' => new UserResource($user), | |
| 'message' => 'Foto atualizada com sucesso!', | |
| ], 200); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment