Laravel upload image from API - laravel

I'm trying to upload an image using the API. Even though, after running the first test, the database just stored the directory and not the file-name, worst part, it stored all directories that come before the one that is needed to store the image.
The code I'm using for the store is the following one:
public function store(Request $request)
{
$image = $request->file('image');
if($image == null){
$imagesDir = 'subjectImgs/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$fileDir = $images[array_rand($images)];
$path = $fileDir;
} else {
$path = $image->storeAs('uploads/images/store/', $image->getClientOriginalName(), 'public');
}
$subject = new Homework([
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$subject->save();
return response()->json([
"code" => 200,
"message" => "Homework added successfully"
]);
}
I'm uploading from a mobile device, I believe this info is also important (?) Same issue when in the simulator.

You are saving $path into $subject->image that is equal to public_path() . '/uploads/images/store/';. You should add $file->getClientOriginalName() if you want the filename :
$subject = new Homework([
...
'image' => $path . $file->getClientOriginalName(),
...
]);

You are settings 'image' => $path, and before that $path = public_path() . '/uploads/images/store/'; which yields the expected results.
Now if you want to only save from a form input, you can use the following code:
$image = $request->file('image');
$path = $image->storeAs('uploads/images/store/', $image->getClientOriginalName(), 'public');
Where 'public' is the default public filesystem as described in the doc here: https://laravel.com/docs/7.x/filesystem#the-public-disk

Related

Laravel form image not getting recognized as file

I'm making an edit page for users using Vue + Laravel rest-api and I'm having a hard time linking an image to the image field of the users table.
The first issue is that it's not recognizing the image as a file despite adding enctype="multipart/form-data" to the form. I looked up some solutions, but haven't found something useful.
The console.log(this.form.newimage) results in newimage: "data:image/jpeg;base64,/9j/4AAQS... so I pressume the format of it is good.
Backend UserController:
public function update(Request $request, $id) {
$validatedData = $request->validate([
'name' => 'nullable|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$id,
'phone' => 'nullable|numeric|digits_between:5,15',
'address' => 'nullable|string|max:255',
'postal_code' => 'nullable|numeric|digits_between:3,200',
'country_id' => 'nullable|string|max:255',
'image' => 'nullable',
'newimage' => 'nullable|file',
]);
$data = array();
(...)
if($request->hasFile('newimage')) {
$destination_path = 'public/images';
$avatar = $request->file('newimage');
$imagename = $avatar->getClientOriginalName();
$path = $request->file('newimage')->storeAs($destination_path, $imagename);
$data['image'] = $filename;
}
User::where('id', $id)->update($data);
}
use store file fun
if($request->image)
{
$request->file('image')->store('image','public');
}

How to upload multiple images in laravel so I can get them in frontend?

I want to do multiple image uploads in my laravel but so far i get errors like image must be image ... is chaos really ... help please???
public function store(Request $request) {
$request->validate([
'name' => 'required',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
'image.*' => 'image',
'description' => 'required',
'quantity' => 'required',
]);
$imgData = [];
if($request->hasfile('image')) {
foreach($request->file('image') as $file)
{
$path = '/images/phones';
$date = Carbon::now();
$tempName = env('APP_URL') . '/storage' . $path . '/'. $date->year.'/' . time() . '.' . $file->getClientOriginalName();
$filename = time() . '.' . $file->getClientOriginalName();
$filePath = $path . "/$date->year";
$file->storeAs( $filePath, $filename, 'public');
$imgData[] = $tempName;
}
$phones = new Phone;
$phones->name = $request->name;
$phones->description = $request->description;
$phones->quantity = $request->quantity;
$phones->price = $request->price;
$phones->brand_id =$request->brand_id;
$phones->image = json_encode($imgData);
$phones->save();
return redirect()->route('phones.index')
->with('success','Product has been created successfully.');
}
So far I get this error that image must be image and another error is displaying required extensions!!

Save image to database

I want to save image name to database but it always save to C:\xampp\tmp\phpAB3A.tmp. btw im not using xampp, im using laragon.How to change the path? i want to save to storage/app/public
'name'=> 'required',
'email' => 'required',
//'logo' => 'required',
$imageName = time().'.'.request()->logo->getClientOriginalExtension();
request()->logo->move(storage_path('app/public'), $imageName);
Company::create($request->all());
return redirect()->route('company.dashboard')->with('Success');
In your Company::create you have to define the path... Something like:Company::create([
'path' => torage_path('app/public',$imageName),....]);
I'm using laravel 5.8 and this code worked for me.
In controller
<?php
public function store()
{
// I did like this, because storeLogo method is reusable
$data = request()->validate([ /* ... */ ]);
$company = Company::create($data);
$this->storeLogo($company);
// but you can do like this
$data = request()->validate([ /* ... */ ]);
if (request()->has('logo')) {
$data['logo'] = request()->logo->store('', 'public');
}
$company = Company::create($data);
}
private function storeLogo(Company $company)
{
if (request()->has('logo')) {
$company->update([
'logo' => request()->logo->store('', 'public'),
// logo file is stored at /storage/app/public/
]);
}
}
$input = $request->all();
$fileName = '';
if ($request->hasFile('logo')) {
$destinationPath = storage_path('app/public');
$file = $request->logo;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
}
$input['logo'] = $fileName;
Company::create($input);

Call to a member function move() on null in laravel

I'm new to laravel. I get the following error when uploading a file:
Call to a member function move() on null
$file = $request->file('img');
$destinationPath = base_path('\public\img');
$file->move($destinationPath . $file->getClientOriginalName());
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img'),
]);
Why dont You Try it like this ?
if ($request->hasFile('img')) {
$image = $request->file('img');
$teaser_image = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $img);
} else {
dd('Request Has No File');
}
and For Your Store :
$dialer = Dialer::create([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img') ?? null,
]);
You Can remove ??null for making sure that you get The image And store it in database but You can Even place It To make it Optional for the User To insert img or not . hope this helps
EDIT
According to your comment i guess you may have 2 problems :
first one be sure that you have and input that named 'img' that sends the image and the secound is that be sure to add the multi enctype to your form so that form can send image like below :
enctype="multipart/form-data"
so your form should be like this :
<form action="someRoute" method="post" enctype="multipart/form-data">
if ($request->hasFile('img')) {
$image = $request->file('img');
// print_r($image);
$image_name = time().'.'.$image->getClientOriginalExtension();
// echo $image;
// exit(0);
$destinationPath = base_path('Uploads');
$image->move($destinationPath, $image_name);
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $image_name,
]);
$dealer->save();
Session::flash('msg','Data Added successfully');
Session::flash('type','success');
return redirect('dealer-master');
// // echo $image;
// // exit(0);
// $destinationPath = base_path(' Uploads');
// $image->move($destinationPath, $image_name);
}
else {
Session::flash('msg','Please Check the data');
Session::flash('type','fail');
return redirect('dealer-master');
// echo $request;
}
I Findout my mistake This is working good Thank U Guys...!
It's work form me
if($request->img){
$fileName = time() . '.' . $request->img->extension();
$request->img->move(storage_path('app/public/img'), $fileName);
}
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $fileName ?? null,
]);
$dealer->save();

Laravel user post image upload error

I have error while i am uploading Post Image I can save picture on my computer but in my database filename is distorted.
Here is my PostsController
public function store(Request $request, User $user, Image $image)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'body' => 'required'
]);
if( $request->hasFile('image') ) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)->save( public_path('uploads/images/' . $filename ) );
}
$image = $filename;
auth()->user()->publish(
new Post(request(['body', 'image'])));
return redirect('/');
}
The problem is that you try to insert the wrong variable into your database table. So, improve your code like this:
auth()->user()->publish(
new Post(['photo' => request('body'), 'image' => $image])
);

Resources