Multiple Image Upload System - php

I am trying to work with uploading multiple images on my project but it is not saving into the database
public function store(Request $request)
{
//validate
$this->validate($request, [
'subject'=>'required|min:10',
'tags' => 'required',
'body' => 'required|min:20',
'filename' => 'sometimes',
'filename.*' => 'file|image|mimes:jpeg,png,jpg,gif,svg|max:5000'
]);
//store
$news=auth()->user()->news()->create($request->all());
$news->tags()->attach($request->tags);
$this->storeImage($news);
//redirect
return redirect()->route('news.index');
}
private function storeImage($news)
{
if (request()->has('image')) {
foreach (request()->file('filename') as $file) {
$news->update([
'filename' => request()->filename->store('uploads', 'public'),
]);
}
}
}
Upload HTML:
<div class="form-group">
<label for="image"><b>Select Image To Add</b></label>
<input type="file" name="filename[]">
</div>
How can I make the file save into the database as it is not saving to the database at all? Could anyone help me to solve this problem please?

It is not a good idea to save images in the database. Keep the files in your public folder on the server and save the file paths in the database only.
update your form like this
<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/store-image">
add multiple to the input
<div class="form-group">
<label for="image"><b>Select Image To Add</b></label>
<input type="file" name="filename[]" multiple >
</div>
update your storeImageFunction Like this
public function storeImage(request $request) {
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image',$name);
$images[]=$name;
}
}
}
Now, you have got all the image paths in the images array.

Related

Laravel errors while storing a file

I am working on a laravel crud project. Now i want to store files like .xlsx and .docx
But i keep getting errors in my controller and browser:
Controller:
public function store(Request $request)
{
$request->validate([
'title'=>'required',
'description_short'=>'',
'description_long'=>'',
'file'=>'',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$fileName = $request->file->getClientOriginalName();
$filePath = 'files/' . $fileName;
$path = Storage::disk('public')->put($filePath, file_get_contents($request->file));
$path = Storage::disk('public')->url($path);
$file = new File([
'title'=> $request->get('title'),
'description_short'=> $request->get('description_short'),
'description_long'=> $request->get('description_long'),
'file'=>$request->get('file'),
'language_id'=> $request->language_id,
]);
$file->save();
return back();
}
Here i get the error: Undefined method 'url'
Create page:
<form method="post" action="{{ route('admin.language.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">{{('name')}}</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="value">{{('file')}}</label>
<input type="file" class="form-control" name="file"/>
</div>
<button type="submit" class="btn btn-primary">Add language</button>
</form>
the browser error i get is : Call to a member function getClientOriginalName() on string.
if i need to provide more information i will gladly do so!
file is reserved keyword in Request class to get submitted Files in post method.
You can not use file in input. So first you have to change file name in input box.
After that you can do like below.
$request->file('file_input_name')->getClientOriginalName();
$file = $request->file->getClientOriginalName();
fixed it

File not uploading

I was working on a project and was trying to develop a file uploading system for skins.
When I tried to upload my skin, I was given "Call to a member function storeAs() on null"
public function uploadSkin(Request $request)
{
/* $request->validate([
'skins' => 'required|mimes:png|max:1024',
]); */
$storage_dir = storage_path('app/skins');
$request->file('skins')->storeAs($storage_dir, Auth::user->name . '.png');
return route('settings')->with('success', 'skin uploaded :)');
}
Form code:
<form method="post" enctype="multipart/form-data" action="/settings">
#csrf
<br/>
<div class="form-group">
<input type="file" class="form-control-file" id="skins" name="skins" required>
</div>
<button type="submit" class="btn btn-success">Upload</button>
</form>
To store a file like an image or any kind of files you can use a code like this:
public function uploadSkin(Request $request){
$image = $request->file('skins');
if ($image != null) {
$image->move('uploads/skins/', Auth::user()->name . $image->getClientOriginalExtension());
}
return route('settings')->with('success', 'skin uploaded :)');
}
To uppload a file there are various ways in the laravel but for now you can try this to simply move your file to your directory:
if($files= $request->file('skins')){
$files->move('uploads/skins/', Auth::user->name . '.png');
}

Laravel 5.6 upload image

I want to upload images with laravel:I created the field in mysql:
imagepath varchar 250
Created the form:
<form method="post" id="formId" action="/ticket" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group ">...other fields
<div class="form-group">
<input type="file" class="form-control-file" name="imageFile" id="imageFile" aria-describedby="fileHelp">
</div>
In my controller:
public function store(Request $request)
{
$fileName = request()->imageFile->getClientOriginalExtension();
dd($fileName);//echos ".jpg"
$tickes = Users::create(['imagePath' => $fileName]);
}
However my db is always null!I want to store it in my public/storage folder in Laravel.
Please help!
you can use this code for upload image to `public/storage/ directory :
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
# save to DB
$tickes = Users::create(['imagePath' => 'storage/'.$name]);
$request->file('input_img')->move("storage", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
This code is only saving the file extension, not the image path.
You need to save the file to storage before your database can get a path to it.
Laravel has really good documentation and this link will help you figure this out. https://laravel.com/docs/5.6/filesystem

php - How to make file uploaded only image - Laravel

Hello im newbie in laravel so i really need some help. I want to create a code where only the image that can upload other files can not, I have tried to use the code input file but when I try to upload the zip file file it still uploaded so I really need help
This is my table code
<div class="col-sm-5">
{!! Form::label('photo', 'Photo:') !!}
<input type='file' name='photo' class='form-control' accept = 'image/jpeg , image/jpg, image/gif, image/png'>
And this is my Controller
public function store(CreateBannerRequest $request)
{
$input = $request->all();
//get original file name
if($request->photo == NULL)
{
Flash::error('Image must be filled');
return back();
}
$filename = Input::file('photo')->getClientOriginalName();
$input['photo'] = $filename;
$banner = $this->BannerRepository->create($input);
//upload file
Input::file('photo')->move($this->path, $filename);
Flash::success('Banner saved successfully.');
if (empty($banner)) {
Flash::error('No image available');
return redirect(route('banner.index'));
}
return redirect(route('banner.index'));
}
You have code at front end like this:
View
<form action="{{URL::to('upload/photo')}}" class="form-horizontal" method="POST" role="form" enctype="multipart/form-data">
<input type="file" name="photo">
<button class="btn btn-default pull-right" type="submit">Create</button>
</form>
Route
Route::post('upload/photo','TestController#uploadPhoto');
TestController
public function uploadPhoto(Request $request)
{
$this->validate($request, [
'photo' => 'mimes:jpeg,png,bmp,tiff |max:4096',
],
$messages = [
'required' => 'The :attribute field is required.',
'mimes' => 'Only jpeg, png, bmp,tiff are allowed.'
]
);
// Now save your file to the storage and file details at database.
}
I hope, you undestand.
you can do it with validation throuhg mimes:jpeg and the other types such as png etc. lookup laravel validation on the documentation page

FileNotFoundException in laravel

In laravel i am making an application that uploads a file and the user can download that same file.
But each time i click to upload i get this error.
FileNotFoundException in File.php line 37: The file
"H:\wamp64\tmp\phpF040.tmp" does not exist
my view code is this:
#extends('layouts.app')
#section('content')
#inject('Kala','App\Kala')
<div class="container">
<div class="row">
#include('common.errors')
<form action="/addkala" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name">
<input type="text" name="details">
<input type="file" name="photo" id="photo" >
<button type="submit">submit</button>
</form>
</div>
</div>
#endsection
and my controller
public function addkalapost(Request $request)
{
$rules = [
'name' => 'required|max:255',
'details' => 'required',
'photo' => 'max:1024',
];
$v = Validator::make($request->all(), $rules);
if($v->fails()){
return redirect()->back()->withErrors($v->errors())->withInput($request->except('photo'));
} else {
$file = $request->file('photo');
$fileName = time().'_'.$request->name;
$destinationPath = public_path().'/uploads';
$file->move($destinationPath, $fileName);
$kala=new Kala;
$kala->name=$request->name;
return 1;
$kala->details=$request->details;
$kala->pic_name=$fileName;
$kala->save();
return redirect()->back()->with('message', 'The post successfully inserted.');
}
}
and i change the upload max size in php.ini to 1000M.
plz help
im confusing
I'll recommend you using filesystems for that by default the folder is storage/app you need to get file from there
if your file is located somewhere else you can make your own disk in config/filesystems e.g. 'myDisk' => [
'driver' => 'local',
'root' =>base_path('xyzFolder'),
],
and you can call it like
use Illuminate\Support\Facades\Storage;
$data = Storage::disk('myDisk')->get('myFile.txt');
this is obviously to get file and you can perform any other function by following laravel docs.

Categories