Undefined variable: image_name Laravel 5.4 - php

I want to upload and display image, but i get error
Undefined variable: image_name
This is my controller
$supply = new DataSupplyProcess;
if($request->hasFile('supply_photo')){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($photo->fails()){
return redirect()->back()->with('warning', 'Image size should be 2MB or less');
}
$image = $request->file('supply_photo');
$image_name = rand().'.'. $image->getClientOriginalExtension();
$destination_path = public_path('/item');
$image->move($destination_path, $image_name);
//dd($image);
}
$supply->item = $request->item;
$supply->supply_details = $request->supply_details;
$supply->tgl_request_date = $request->tgl_need_date;
$supply->tgl_need_date = $request->tgl_need_date;
$supply->employee_id = $id;
$supply->id_approved_by = $manager->employee_manager_id;
$supply->is_approved = 0;
$supply->is_final_approved = 0;
$supply->supply_photo = $image_name;
$supply->save();
This Is My View
<label for="supply_photo">Photo</label>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" class="form-control" name="supply_photo">

In your controller, try something like:
if(Input::file('supply_photo') !== null){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
...
}
I think this post can provide more info

when ever you pass variable like this with IF condition assign default value first.
so you won't get error if image not selected.
and in your cause check first you get image or not
dd($image = $request->file('supply_photo'));
$image_name = NULL;
if($request->hasFile('supply_photo')){
$image = $request->file('supply_photo');
$image_name = rand().'.'. $image->getClientOriginalExtension();
$destination_path = public_path('/item');
$image->move($destination_path, $image_name);
}
$supply->supply_photo = $image_name;
$supply->save();

$supply = new DataSupplyProcess;
if($request->hasFile('supply_photo')){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($photo->fails()){
return redirect()->back()->with('warning', 'Image size should be 2MB or less');
}
//$original_name=$request->file('supply_photo')->getClientOriginalName();
//$size=$request->file('supply_photo')->getSize();
$extension=$request->file('supply_photo')->getClientOriginalExtension();
$filename=uniqid().'.'.$extension;
$imagepath=url('/item/'.$filename);
$path=$request->file('supply_photo')->storeAs(public_path('/item'),$filename);
}

Related

how to upload file in laravel with taking the desired name

I am facing an error while uploading a file it is saying that the Undefined variable: filenametostore.
This is my controller :
if(!$validator->fails()){
$cate = Product::where('name','=',$request->product_name)->first();
if($cate){
$arr = array('status'=>'false-1','message'=>'Product name already exist');
}else{
$cat = new Product();
$cat->name = $request->product_name;
$cat->category_id = $request->product_category;
$cat->brand_id = $request->product_brand;
$cat->quantity = $request->product_quantity;
$cat->buy_per_piece = $request->product_buying_per_piece;
$cat->sell_per_piece = $request->product_selling_per_piece;
if($request->hasFile('thumbnail')){
$filenameExt = $request->file('thumbnail')->getClientOriginalName();
$filename = pathinfo($filenameExt,PATHINFO_FILENAME);
$extension = $request->file('thumbnail')->getClientOriginalExtension();
$filenametostore = $filename.'_'.time().'.'.$extension;
$request->file('thumbnail')->move(public_path('images'), $filenametostore);
}
$cat->image = $filenametostore;
$cat->save();
$arr = array('status'=>'true','message'=>'Successfully Inserted');
}
}else{
$arr = array('status'=>'false','message'=>$validator->errors()->all());
}
please help me to rectify the error

how to make first item of array active and rest inactive

I have multiple image uploader and i want only the first image to get true value and other false. I mean I have DB field name 'isPrimary' , so when I upload multiple images I want only first image get true value and other images get false value.
<div class="col-lg-12 p-t-20">
<label class="control-label col-md-3">Upload Room Photos</label>
<input type = "file" id = "image" name="image[]" multiple class="file" data-overwrite-initial="false"
data-min-file-count="1">
</div>
This is my controller for image store
if($request->hasfile('image')) {
$image = $request->image;
if(count($image) === 1){
$isPrime = $dataa['isPrimary'] = true;
}else{
///So here i need logic to make ('isPrimary') field to be true in only first image when there is multiple images is uploaded
}
foreach ($image as $photo) {
// dd($photo);
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
//
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=>$isPrime,
];
Image::create($dataa);
}
}
Sorry For my English, I am not good at cause it's my second language .
Thanks, in advance.
Try this
foreach ($image as $photo) {
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=> (\Arr::first($image) == $photo) ? true : false,
];
Image::create($dataa);
}
$is_prime = true;
foreach ($image as $photo) {
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=>$isPrime,
];
$is_prime = false;
}
Image::create($dataa);

restrict number of files to upload for particular users

In my property section I have two property types:
Freemium
Premium
I want to restrict users to upload only 5 images for Freemium property type while for Premium properties a user can upload infinitive number images and videos.
Must needed some suggestions.
Here is my image upload part :
public function postProperty(PropertyRequest $request)
{
$user = User::where('id', $request->user->user_id)->first();
if(!empty($user))
{
$data['user_id'] = $user->id;
$data['type'] = $request->type;
$data['category'] = $request->category;
$data['area'] = $request->area;
$data['price'] = $request->price;
$data['description'] = $request->description;
//dd($data);
$property = Property::create($data);
//$property['flag'] = false; // if (flag = false, property = freemium) else (flag = true, property = premium ))
$urls = new PropertyImage();
if ($request->hasFile('url'))
{
$files = $request->file('url');
foreach($files as $file)
{
$mime = $file->getMimeType();
//$property['flag'] = $property->account == 1 ? false : true;
if($mime == 'image/jpeg')
{
$fileName = $file->getClientOriginalName();
$destinationPath = public_path() . '/images/';
$file->move($destinationPath, $fileName);
$urls->url = '/public/images/' . $fileName;
$url_data = [
'property_id' => $property->id,
'url_type' => 1,
'url' => $urls->url,
];
$urls->create($url_data);
}
elseif($mime == 'video/mp4')
{
$fileName = $file->getClientOriginalName();
$destinationPath = public_path() . '/videos/';
$file->move($destinationPath, $fileName);
$urls->url = '/public/videos/' . $fileName;
$url_data = [
'property_id' => $property->id,
'url_type' => 2,
'url' => $urls->url,
];
$urls->create($url_data);
}
}
}
return Utility::renderJson(trans('api.success'), true, $property, $urls );
}
}
You can use laravel validation to restrict user to some number of files as shown below
//If user is Freemium then restrict him
if (!$property['flag']) {
$messages = [
"url.max" => "files can't be more than 3."
];
$this->validate($request, [
'url' => 'max:3',
],$messages);
}

Retrieve uploaded photo laravel

So I managed to upload multiple images but now I need to display it in a page I tried something like the code below but it says "unidentified variable: photo"
<img class="img-responsive" src="/images/{{ $photo->fileName }}" >
Here's my upload code, updated my code.
Route::post('space/add', array('before' => 'auth', function()
{
$data = Input::all();
$provider_id = Auth::user()->id;
$spaces = Space::where('provider_id', '=', $provider_id)->get();
$space = new Space;
....
$space->save();
$file = Input::file('image');
$provider_email = Auth::user()->email;
// $space = Space::find($id);
$rules = array(
'file' => 'required|mimes:png,gif,jpeg'
);
$validator = \Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
foreach(Input::file('image') as $file)
{
$ext = $file->guessClientExtension(); // (Based on mime type)
$name = $file->getClientOriginalName();
$fileName = md5($name) . '.' .$ext;
$destinationPath = 'images/' . $provider_email;
$file = $file->move($destinationPath, $fileName);
$photo = new Image;
$photo->provider_id = $provider_id;
$photo->spaces_id = $space->id;
$photo->filename = $fileName;
$photo->path = $destinationPath;
$photo->save();
}
} else{
//Does not pass validation
$errors = $validator->errors();
}
return Redirect::to('user/spaces')->with(array('spaces' => $spaces, 'photo' => $photo));
}));
you need to do something like
return View::make('yourviewname')->with('photo', $photo);
this will be in your route or your controller depending on your setup
EDIT:
You will access your varaible in user/spaces through $photo = Session::get('photo') from user/spaces you will pass that variable in your with i.e. ->with('photo', $photo)

Laravel Insert data without select file

Ok, when insert data in the database, in the form of my field is to image, but if you insert data without image, appears to me the following error.
Call to a member function getClientOriginalName() on a non-object
public function store() {
$unos = Input::all();
$obavezno = array('name' => 'required',
'number' => 'required|unique:os',
'zajednica' => 'required',
'slika' => 'image|size:3000',
);
$valid = Validator::make($unos, $obavezno);
if($valid->passes()) {
$biraci = new Biraci();
$filename = Input::file('slika')->getClientOriginalName();
$biraci->name = Input::get('name');
$biraci->slika = Input::file('slika')->move('public/uploads', $filename);
$biraci->path = $filename;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
return Redirect::to('biraci/dodaj')->with(array('ok' => 'Birac je uspjesno dodat.'));
} else {
return Redirect::to('biraci/dodaj')->withErrors($valid);
}
}
Try this:
if($valid->passes()) {
$biraci = new Biraci();
if (Input::hasFile('slika')) {
$filename = Input::file('slika')->getClientOriginalName();
}
$biraci->name = Input::get('name');
$biraci->slika = isset($filename) ? Input::file('slika')->move('public/uploads', $filename); : null;
$biraci->path = isset($filename) ? $filename : null;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
}
$filename = Input::file('slika')->getClientOriginalName();
// change to
$filename = Input::hasFile('slika') ? Input::file('slika')->getClientOriginalName() : null;

Categories