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)
Related
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);
}
I want to Update an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image
Iam using Laravel 5.7
Here is my create, the create is success
public function store(Request $request)
{
//
$product = new \App\Product;
$product->product_name = $request->get('product_name');
$product->desc = $request->get('desc');
$product->stock = $request->get('stock');
$product->price = $request->get('price');
$product->category = $request->get('category');
$img = $request->file('img');
$new_name = rand() . '.' . $img->getClientOriginalExtension();
$img->move(public_path('img'), $new_name);
$product->img = $new_name;
$product->save();
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
Here is my update
public function update(Request $request, $id)
{
//
$product = $request->all();
$product= \App\Product::find($id);
$new_name = $request->file('img')->getClientOriginalName();
$destinationPath = 'img/';
$proses = $request->file('img')->move($destinationPath, $new_name);
if($request->hasFile('img'))
{
$product = array(
'product_name' => $product['product_name'],
'desc'=> $product['desc'],
'stock'=> $product['stock'],
'price'=> $product['price'],
'category'=> $product['category'],
'img' => $new_name,
);
$product->save() ;
return redirect('admin')->with('success', 'Data Produk telah ditambahkan');
}
}
Call to a member function getClientOriginalName() on null
I think there is no image file attach while updating. You can use my code as reference.
Don't forget to check for the input field in your update field.
First check if there is image file or not. Then, go for getting name, extension and other staff.
public function update($id, Request $request)
{
$input = $request->all();
$product= \App\Product::find($id);
if (empty($product)) {
Flash::error('product not found');
return redirect(route('products.index'));
}
if ($request->hasFile('product_img')) {
$fileNameWithExt = $request->file('product_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('product_img')->getClientOriginalExtension();
$new_product_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('product_img')->move('images/products', $new_product_img);
Storage::delete('products/'.$product->product_img);
$input['product_img']= $new_product_img;
}
$product= $this->productRepository->update($input, $id);
Flash::success('product updated successfully.');
return redirect(route('products.index'));
}
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);
}
I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
I have been having issues with my image upload input. I am attempting to create a file upload input into my Laravel 5 project but I am running into problems with the path that is saved into the database image table.
The form is working and is posting, however, when the database saves the path to the image it is inputting: /Applications/MAMP/tmp/php/phptvwTYW instead of taking just the file name.
Additionally, the file is being moved to the correct public/img folder.
Code
public function store(PostRequest $request)
{
$this->createPost($request);
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
Here is the sample Controller Function currently using in my project
public function postCreateInternal(CreateDocumentInternalRequest $request) {
$data_information = $request->only(['title', 'assigned_to', 'folder_id', 'document_source']);
if ($request->hasFile('file_name') && $request->file('file_name')->isValid()) {
$document = $request->file('file_name');
#creating file Name
$mytime = Carbon::now();
$date_now = $mytime->toDateTimeString();
$date_now = $this->prepareFileNameString($date_now);
$document_extension = $document->getClientOriginalExtension();
$document_name = $this->prepareFileNameString(basename($document->getClientOriginalName(), '.' . $document_extension));
$document_fullName = $document_name . "_" . ($date_now) . "." . $document_extension;
$data_information['file_type'] = $document->getMimeType();
$data_information['file_size'] = $document->getSize();
$data_information['file_name'] = $document_fullName;
$data_information['file_download_type'] = "Internal";
$document->move(public_path() . '/uploads/documents/', $document_fullName);
}
if ($pot = $this->document->create($data_information)) {
$this->notification_admin->sendCreateDocument($data_information);
return redirect()->route('documents')->with('success', trans('document.create.msg_success'));
// return redirect()->route('update/document', $pot->id)->with('success', trans('document.create.msg_success'));
}
return redirect()->route('create/document')->with('error', trans('document.msg_error'));
}
CreateDocumentInternalRequest basically using for File and other data validation as per Laravel 5
And View File seems to like:
{!! Form::open(["class"=>"form-horizontal","data-parsley-validate"=>"data-parsley-validate",'role'=>'form','files'=>true]) !!}
<div class="form-group required {{ $errors->first('file_name', ' has-error') }}">
{!!Form::label('file_name', trans('document.label.file_name'), array('class' => 'col-md-4 control-label left-label'))!!}
<div class="col-sm-6">
{!! Form::file('file_name') !!}
{!! $errors->first('file_name', '<span class="help-block">:message</span>') !!}
</div>
</div>
{!! Form::close() !!}
In my current implementation, first i'm checking file uploaded, rename filename with current timestamp and re upload my desire location.
If you need any help my provided method let me know to improve in better way.
this is very simple way:
public function store(PostRequest $request)
{
$image_name = $request->file('image')->getClientOriginalName();
$request->file('image')->move(base_path().'/public/images', $image_name);
$post = ($request->except(['image']));
$post['image'] = $image_name;
Post::create($post);
Session::flash('success_message', 'Post has been added successfully!');
return redirect('teacher');
}
public function profileUpdate($id)
{
if(!Entrust::can('profile_update_employee'))
return Redirect::to('/dashboard')->withErrors(Config::get('constants.NA'));
if(!Helper::getMode())
return Redirect::back()->withErrors(Config::get('constants.DISABLE_MESSAGE'));
$employee = User::find($id);
if(!$employee)
return Redirect::to('employee')->withErrors(Config::get('constants.INVALID_LINK'));
$rules = array(
'photo' => 'image|image_size:<=2000|max:100000',
'date_of_birth' => 'date',
'date_of_joining' => 'date',
'date_of_leaving' => 'date',
'employee_code' => 'required|unique:profile,employee_code,'.$employee->Profile->id.',id'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
return Redirect::to('/employee/'.$id."#basic")->withErrors($validator);
Activity::log('Profile updated');
$profile = $employee->Profile ?: new Profile;
$photo = $profile->photo;
$data = Input::all();
$profile->fill($data);
if(Input::get('date_of_birth') == '')
$profile->date_of_birth = null;
if(Input::get('date_of_joining') == '')
$profile->date_of_joining = null;
if(Input::get('date_of_leaving') == '')
$profile->date_of_leaving = null;
if (Input::hasFile('photo') && Input::get('remove_photo') != 1) {
$filename = Input::file('photo')->getClientOriginalName();
$extension = Input::file('photo')->getClientOriginalExtension();
$file = Input::file('photo')->move('assets/user/', $employee->username.".".$extension);
DB::insert('insert into ez_profile (id, photo) values ($id, $photo)');
$img = Image::make('assets/user/'.$user->username.".".$extension);
$img->resize(200, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save('assets/user/'.$user->username.".".$extension);
$profile->photo = $employee->username.".".$extension;
} elseif(Input::get('remove_photo') == 1){
File::delete('assets/user/'.$profile->photo);
$profile->photo = null;
}
else
$profile->photo = $photo;
$employee->profile()->save($profile);
return Redirect::to('/employee/'.$id.'/#basic')->withSuccess(Config::get('constants.SAVED'));
}
Try this:
public function store(PostRequest $request, Post $post) {
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
$post->create([
'field1' => $val1,
'imageField' => $filename,
'field2' => $val2
]);
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
I found the solution to my question.
I had to make some changes to the store and createPost functions within my controller to make this work.
For the controller I have:
public function store(PostRequest $request)
{
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
$this->createPost($request, $filename);
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
private function createPost(PostRequest $request, $new_url)
{
$post = Auth::user()->posts()->create($request->all());
$post->image_url = $new_url;
$post->save();
$this->syncTags($post, $request->input('tag_list'));
return $post;
}
I hope this helps anyone else that may be running into this same problem.
Thank you everyone for the help!
its because you save before moving,
//before moving
$request->file('image_url')->getPath(); // returns Applications/MAMP/tmp/php/php...
to have the full path of your new moved file you can do this
//After moving
$res = $request->file('image_url')->move( $destinationpath,$filename );
$my_new_path = $res->getPath(); // returns [public_path]/img/filename.jpg
you can save it by update your post after moving the file, or use event to move it when saving
look here http://laravel.com/docs/master/eloquent#events