I am trying to upload an image to the database with a path created in public (i.e., uploads/images) but unfortunately, it is not displaying any error, and the image is not uploaded or saved to the directory.
Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Image;
class ImagesController extends Controller
{
public function index()
{
return view('image');
}
public function upload(Request $request)
{
$this->validate($request, [
'images' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('images');
$input['imagename'] = time() . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/images');
$img = Image::make($image->getRealPath());
$img->resize(100, 100, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath . '/' . $input['imagename']);
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
$this->postImage->add($input);
if (!empty($input['imagename'])) {
return response()->json([
'success' => true,
'data' => $input['imagename']->toArray()
]);
}
return true;
}
}
Route
Route::post('upload', 'ImagesController@upload');
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $fillable = ['image'];
}
Try to adopt this style then run
php artisan storage:link
Also, change your controller to this
public function upload(Request $request)
{
$img = new Image();
$validation = $request->validate([
'title' => 'string',
'image' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048'
]);
$file = $validation['image']; // get the validated file
$extension = $file->getClientOriginalExtension();
$filename = 'mm-image-' . time() . '.' . $extension;
$path = $file->storeAs('/uploads/images', $filename);
$img->image = $request->image;
$img->title = $path;
dd($img);
if (!empty($img)){
return response()([
'success' => true,
'data' => $img->toArray()
]);;
}
}