Skip to content

Commit

Permalink
Impove image/ avatar operation
Browse files Browse the repository at this point in the history
  • Loading branch information
Priatmoko committed Apr 4, 2019
1 parent d112bc9 commit 39217f6
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions app/Http/Controllers/Admin/Profile/FormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

//load the user model
use App\User;

class FormController extends Controller
Expand All @@ -27,35 +28,40 @@ public function store(Request $r)
if ($validation->fails())
return response()->json(['errors'=>$validation->errors()], 422);

//passed input continue to run update operation
$user = User::find($r->input('id'));

//check the existance of avatar upload
if ($r->has('avatar')){
$file = $r->file('avatar');
$filename = $r->input('username').'.'.$file->extension();
$path = public_path('files/admin/users/');
$this->moveFile($file, $filename, $path);
$this->moveFile($file, $filename, $path, $user);
}
//passed input continue to run update operation
$user = User::find($r->input('id'));
//Assign new data
$user->name = $r->input('name');
$user->email = $r->input('email');


//validate the existing of file name
if (isset($filename) && $filename!="")
$user->avatar = $filename;

//save the changing
if ($user->save()){

//creating thumbnail
if (isset($filename) && $filename!=""){
$data['avatar']=$filename;
\Image::make($path.$filename)
->fit(200)
->save($path.'thumb-'.$filename);
$data['image']=$this->toBase64($path.'thumb-'.$filename);
}
//return the success message
$response =['status'=>'success',
'data'=>(isset($data)?$data:''),
'message'=>''];
return response()->json($response, 200);
}
//return the failed message
return response()->json(['status'=>'error', 'message'=>''], 200);

}
Expand All @@ -65,14 +71,20 @@ public function store(Request $r)
* @param string $filename
* @return void
*/
private function moveFile($file, $filename, $path)
private function moveFile($file, $filename, $path, $user)
{
//validate upload file
if (isset($file) && $file->isValid()){

//check file existing
//check the existing file refer to form input
if (file_exists($path.$filename))
unlink($path.$filename);
//check the existing file refer to exist data
if (file_exists($path.$user->avatar))
unlink($path.$user->avatar);
//check the existing file refer to exist data (thumbnail)
if (file_exists($path.'thumb-'.$user->avatar))
unlink($path.'thumb-'.$user->avatar);

//move the file to the server
$file->move($path, $filename);
Expand Down

0 comments on commit 39217f6

Please sign in to comment.