Skip to content

Instantly share code, notes, and snippets.

@kamleshwebtech
Forked from earth774/Controller.php
Created May 5, 2021 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamleshwebtech/35f484253566de2c24734c159f33132f to your computer and use it in GitHub Desktop.
Save kamleshwebtech/35f484253566de2c24734c159f33132f to your computer and use it in GitHub Desktop.
create upload image in lumen
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
public function uploadImage(Request $request)
{
$response = null;
$user = (object) ['image' => ""];
if ($request->hasFile('image')) {
$original_filename = $request->file('image')->getClientOriginalName();
$original_filename_arr = explode('.', $original_filename);
$file_ext = end($original_filename_arr);
$destination_path = './upload/user/';
$image = 'U-' . time() . '.' . $file_ext;
if ($request->file('image')->move($destination_path, $image)) {
$user->image = '/upload/user/' . $image;
return $this->responseRequestSuccess($user);
} else {
return $this->responseRequestError('Cannot upload file');
}
} else {
return $this->responseRequestError('File not found');
}
}
protected function responseRequestSuccess($ret)
{
return response()->json(['status' => 'success', 'data' => $ret], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
protected function responseRequestError($message = 'Bad request', $statusCode = 200)
{
return response()->json(['status' => 'error', 'error' => $message], $statusCode)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment