I want to make laravel api for multiple file upload when i am uploading then its gives error $data is undefined variable.please help me how to remove this error..?
FileUploadController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
public function uploadFile(Request $request){
$this->validate($request, [
'user_sharing_image' => 'required',
'user_sharing_image.*' => 'mimes:doc,pdf,docx,zip'
]);
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = $request->user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
return back()->with('success', 'Data Your files has been successfully added');
}
}
I am using laravel passport for auth and want to store user_id but do not geting please help me how to resolve both problem from this code
Give it a try
$data = [];
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $key=>$file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[$key] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = Auth::user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
You are getting this error because $data is not defined.
Before foreach loop you can declare it as $data = array();
i think you should use files method to return array of files :
foreach($request->files('user_sharing_image') as $file)
Hello fellow developers
This will work properly
$files = $request->allFiles('imgs');
foreach ($files as $key => $img) {
# code...
$filename = request()->getSchemeAndHttpHost() . '/assets/images/users/upload/profile/photos/' . time() . '.'. $img->extension();
$img->move(public_path('/assets/images/users/upload/profile/photos/'), $filename);
$photos = UserPhoto::create([
'user_id' => $user->id,
'name' => $filename
]);
}
return response()->json([
'status' => true,
'data' => 'Photos Uploaded Successfully!!'
]);
Related
public function update_room_detail(Request $request)
{
$request->validate([
'room_type' => 'required',
]);
if($images = $request->file('room_image'))
{
foreach($images as $item):
$var = date_create();
$time = date_format($var, 'YmdHis');
$imageName = $time.'-'.$item->getClientOriginalName();
$item->move(public_path().'/assets/images/room', $imageName);
$arr[] = $imageName;
endforeach;
$image = implode("|", $arr);
}
else
{
unset($image);
}
RoomDetail::where('id',$request->room_id)->update([
'room_type' => $request->room_type,
'room_image' => $image,
]);
Alert::success('Success', 'Rooms details updated!');
return redirect()->route('admin.manage-room');
}
In the above code I am trying to update image in database table. When I click on submit button then it show Undefined variable: image and when I use $image='' in else part instead of unset($image) then blank image name save. So, How can I solve this issue please help me? Please help me.
Thank You
As per the PHP documentation:
unset() destroys the specified variables.
What this means is that it doesn't empty the value of the specified variables, they are destroyed completely.
$foo = "bar";
// outputs bar
echo $foo;
unset($foo);
// results in Warning: Undefined variable $foo
echo $foo;
You've already discovered how to handle this:
when I use $image='' in else part instead of unset($image) then blank image name save
Fix:
Note : uses Storage library feel free to use any other.
public function update_room_detail(Request $request)
{
$request->validate([
'room_type' => 'required',
]);
$imageNames = array();
if ($request->hasFile('room_image')) {
$images = $request->file('room_image');
foreach ($images as $item) {
$var = date_create();
$time = date_format($var, 'YmdHis');
$imageName = $time . '-' . $item->getClientOriginalName() .".".$item->extension();
$item->storeAs('/public/room-images-path', $imageName);
array_push($imageNames, $imageName);
}
}
RoomDetail::where('id', $request->room_id)->update([
'room_type' => $request->room_type,
'room_image' => $imageNames,
]);
Alert::success('Success', 'Rooms details updated!');
return redirect()->route('admin.manage-room');
}
I want to upload a blogger's profile image but I get an error:
Undefined variable: file_name.
I think it is a controller issue. I don't know why the variable is not defined, though I declared the same variable name.
I restarted the server but it did not work.
So please help me out.
BloggerController.php
public function store(Request $request, User $user_id)
{
$user_id = DB::table('users')->where('id', $user_id)->get();
if ($request->hasfile('image')) {
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$file_name = time() . '.' . $ext;
$file->move('bloggers/', $file_name);
}
$blog = Blog::create(
['user_id' => $user_id],
[
'image' => $file_name,
'introduction' => $request->introduction,
]
);
return redirect(route('blogger'));
}
I also changed the store method.
if ($request->hasfile('image')) {
$file_name = $request->file('image')->getClientOriginalName();
$request->file('image')->storeAs('bloggers/', $file_name);
}
My migration
Schema::create('blogs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('bloggers');
$table->string('image');
$table->string('introduction');
$table->timestamps();
});
To be sure that your variable $fillename is available then change your code to this
if($request->hasfile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = time().'.'.$ext;
$file->move('bloggers/', $filename);
$blog = Blog::create(
['user_id' => $user_id],
[
'image'=>$filename,
'introduction' => $request->introduction,
]
);
}
you must return file address and name in uploader
public function store(Request $request, User $user_id){
$user_id = DB::table('users')->where('id', $user_id)->get();
if($request->hasfile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$file_name = time().'.'.$ext;
$file->move('bloggers/', $file_name);
}
$blog = Blog::create(
['user_id' => $user_id],
[
'image'=>"/bloggers/".$file_name,
'introduction' => $request->introduction,
]
);
return redirect(route('blogger'));
}
i think its work
You tried accessing the variable out of scope. Make it an external variable by declaring it out of the if function as I show below on line 2 of the code.
...
public function store(Request $request, User $user_id){
$file_name="";
$user_id = DB::table('users')->where('id', $user_id)->get();
if($request->hasfile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$file_name = time().'.'.$ext;
$file->move('bloggers/', $file_name);
}
$blog = Blog::create(
['user_id' => $user_id],
[
'image'=>"/bloggers/".$file_name,
'introduction' => $request->introduction,
]
);
return redirect(route('blogger'));
}
...
How to insert multiple images into the table?
Controller
public function save(Request $request)
{
$images = new Image;
$input = $request->file("image");
if($files=$request->file('image')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path("/images/"),$name);
$images[]=$name;
$images->Image = $input->getClientOriginalName();
}
}
$images->save();
$image = Image::find($request->id);
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
I expect to insert images into database, the the error is No message
I think it's better to use mass assignment to insert your image name into the database. The code will be like this :
public function save(Request $request)
{
$images = new Image;
if ($files = $request->file('image')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move(public_path("/images/"),$name);
$images->create(['Image' => $file]);
}
}
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
You must insert it in every loop, if you use the model attribute it will just change every time the loop sets the image name.
public function create(Request $request)
{
$rules = array(
'gallery_album_id'=> 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
);
$input=$request->all();
$image=array();
if($files=$request->file('image')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('images',$name);
$image=$name;
gallery::insert( [
'image'=> $image,
'gallery_album_id' =>$input['gallery_album_name']
]);
}
}
return redirect()->route('gallery')->withStatus(__('Album successfully added.'));
}
I created a form here with Laravel and DropzoneJS and I tried uploading a Gimp file (.xcf) and when it is uploaded it is saved in S3 as the following
<random-name>.
without the "xcf" extension just random name ending with a dot.
Also, I created a text file and renamed it to test.xcf when I tried uploading that file it was uploaded with the .txt extension.
Here is my UploadController.php which handles the upload:
<?php
namespace App\Http\Controllers;
use App\Upload;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function upload(Request $request)
{
$originalName = $request->file('file')->getClientOriginalName();
$fileSize = $request->file('file')->getClientSize();
$path = $request->file('file')->store('documents');
$explode = explode('documents/', $path);
$name = $explode[1];
$uniqueId = $this->generateUniqueId();
$upload = new Upload();
$upload->unique_id = $uniqueId;
$upload->name = $name;
$upload->path = $path;
$upload->original_name = $originalName;
$upload->size = $fileSize;
if ($upload->save())
{
return response()->json([
'original_name' => $originalName,
'size' => $fileSize,
'url' => env('AWS_URL') . $path,
'id' => $uniqueId,
'status' => 'OK'
]);
}
return response()->json(['status' => 'BAD', 'message' => 'There was a problem saving your file.']);
}
public function generateUniqueId()
{
$result = '1';
$result .= rand(100000000, 999999999);
while(Upload::where('unique_id', '=', $result)->first())
{
$result = '1';
$result .= rand(100000000, 999999999);
}
return $result;
}
}
I've got no idea why it's doing that.
I suggest, you generate your own hash for filename, like I do in this code:
$file = $request->file('csv');
$path = $file->storeAs(
'csv',
md5($file->getClientOriginalName()) . $file->getClientOriginalExtension(),
's3'
);
You can also add uniqid() to md5 input
If you're using laravel 5+ then you should get the extension also using this.
$extension = $file->getClientOriginalExtension();
This will work fine.
I try to send attachement files but i get
Cannot use object of type Illuminate\Http\UploadedFile as array
I use laravel 5.4
Someone know why i'm getting this error ?
( I don't upload the file into a directory, i just want to send the file who was requested on my controller )
Hope someone could help , best regards :)
Here my controller :
public function postSendMassive(Request $request){
$files = $request->file('uploads');
$emails = Structure::where('type_structure_id', 4)->pluck('adresse_email_structure');
$subject = $request->subject;
$bodyMessage = $request->texte;
foreach($files as $file) {
$files[] = [
'file' => $file->getRealPath(),
'options' => [
'mime' => $file->getClientMimeType(),
'as' => $file->getClientOriginalName()
],
];
}
Mail::to('test#gmaIL.com')->send(new MassiveEmail($subject , $bodyMessage , $files));
return back()->with('status', "Email envoyé");
}
here my build mail :
public function build()
{
$subject = $this->subject;
$bodyMessage = $this->bodyMessage;
$files = $this->files;
$email = $this->markdown('email.MassiveMail',compact('bodyMessage'))
->subject($subject.'-'.'FFRXIII Licences & Compétitions');
foreach($this->files as $file) {
$email->attach($file['file'],$file['options']);
}
return $email;
}
This is because $request->file('uploads') returns an object and you're trying iterate over it with foreach
If you want to upload multiple files, make sure you're doing something like this:
<input type="file" name="uploads[]" multiple />
And iterate over uploaded files:
foreach ($request->uploads as $file)
This works!
if($request->hasFile('files')){
foreach ($request->files as $file) {
//get file name with extenstion
$fileNameWithExt = $file->getClientOriginalName();
//get just filename
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//get extension
$extension = $file->getClientOriginalExtension();
//file to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload to store
$path = $file->storeAs('${your_storage_path}', $fileNameToStore);
}
}