How to display image after file upload problem with laravel - php

After a succesful file upload, my show.blade doesn't seem to find my images to display.
I've already linked the directory and the image uploads directly to the wished directory.
post Controller
public function store(Request $request)
{
/**
* Validation Rules using Validator class
*/
$rules = [
/*'post_id' => 'required|numeric',*/
'title' => 'required|min:3',
'intro' => 'required|min:3',
'content' => 'required|min:3',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()) {
// dd('validation fail');
return Redirect::back()
->withInput()
->with(
[
'notification' =>'danger',
'message' => 'Something went wrong'
]
)
->withErrors($validator);
}
$post = new Post();
$post->title = $request->input('title');
$post->intro = $request->input('intro');
$post->content = $request->input('content');
$success = $post->save();
/**
* Handle image upload
*/
if($request->hasfile('image') && $success){
$directory = '/post-' . $post->id;
foreach($request->file('image') as $image) {
$name = $image->getClientOriginalName();
$extension = $image ->getClientOriginalExtension();
$fileName = pathinfo($name,PATHINFO_FILENAME) . '-' . time() . '.' . $extension;
$image->storeAs($directory,$fileName,'public');
$image = new Image();
$image->post_id = $post->id;
$image->filename = $fileName;
$image->filepath = $directory;
$image->save();
}
return back()->with([
'notification' => 'succes',
'message' => 'You have created a new post'
]);
}
}
Show blade
#extends('layout')
#section('content')
<div>
<h1 class="title">{{$post->title}}</h1>
<p> {{$post->content}} </p>
<div class="row">
#foreach($post->images as $image)
<div class="col-sm">
<img class="img-fluid" src="{{ asset($image->filepath . '/' . $image->filename) }}" alt="{{ $post->title }}">
</div>
#endforeach
</div>
</div>
<p>Edit</p>
#endsection
when i inspect the element, i get the image's alt which is the $post-> title, but the path seems to be incorrect for some reason.

storeAs function returns path to the stored file relative to the storage. You don't need to concatenate it yourself. Also it can be a problem with a forward slash in the path.
// Store result path to the variable
$path = $image->storeAs($directory,$fileName,'public');
$image = new Image();
$image->post_id = $post->id;
$image->filename = $fileName;
$image->filepath = $path; // Save path returned by the storeAs
$image->save();
Use asset with just that path.
<img class="img-fluid" src="{{ asset($image->filepath) }}" alt="{{ $post->title }}">
Also check your file system configuration. public/storage should be symbolic link to the storage/app/public, otherwise stored files will not be accessible from the web.

give this a try.
<img class="img-fluid" src="src="{{ asset('path/to/image/'. $image->filename) }}"" alt="{{ $post->title }}">
I will rather approve it this way
Get the last inserted post ID
$post_id = post->id;
$image = $request->file('image');
if ($request->hasFile('image'))
{
foreach ($request->image as $img) {
$name = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$fileName = $name . '-' . time() . '.' . $extension;
if (!file_exists('POST/IMAGE')) //Let check if the path doesn't exist
{
mkdir('POST/IMAGE', 0777 , true);// then create one with read/write permission
}
$image->move('POST/IMAGE',$imagename); // Save the file in this folder
}else {
$imagename = 'dafault.png'; // Optional: if none file selected, the use default file.
}
$image = new Image();
$image->post_id = $post_idid;
$image->filename = $fileName;
//$image->filepath = $directory;// You don't really need the save the file name in your DB
$image->save();
}
return back()->with([
'notification' => 'succes',
'message' => 'You have created a new post'
]);
}

Related

how to solve laravel file uploading problem

I tried to upload image on my public folder but i constantl getting error like this
The "C:\xampp\tmp\phpCE7B.tmp" file does not exist or is not readable.
Her is my code that i tried so far
public function create(Register $request)
{
//Registering Students
$student=new Student;
$student->name = $request->input('name');
$student->username = $request->input('username');
$student->email = $request->input('email');
$student->password = bcrypt($request->input('password'));
$student->gender = $request->input('gender');
$student->phone = $request->input('phone');
if ($request->hasFile('image')) {
$file=$request->File('image');
$ext=$student->username. "." .$file->clientExtension();
$path = public_path(). '/images/';
$file->move($path,$ext);
$student->image = $ext;
}
$student->save();
}
it saved my info with image in database but after storing gives me the error.Please help me to solve this
"UPDATE"
I dont Know what is happening to me, but now its working autometically
I have the same problem when i'm trying to upload image to public path.
I solved the problem by defining a file system disk in config (filesystems) like that:
'YourDiskName' => [
'driver' => 'local',
'root' => public_path(),
],
then you can upload images to this path by using StoreAs method:
$file = $file->storeAs(YourPathInPublic, YourFileName, [
'disk' => 'YourDiskName'
]);
// Get Form Image
$image = $request->file('image');
$slug = str_slug($request->name);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
if (!file_exists('storage/uploads/post'))
{
mkdir('storage/uploads/post',0777,true);
}
$image->move('storage/uploads/post',$imagename);
}else{
$imagename = "default.png";
}
//getting coding
public function index(){
return view('admin.post.index',compact('posts'));
}
// show code
<div class="body">
<img class="img-responsive img-thumbnail" src="{{ asset('storage/uploads/post/'.$post->image) }}" >
</div>
I also had the same issue when I use public_path()
Try something like this rather than using public_path. Actually there is nothing wrong with your code. But this happens most of the time due to permission levels. As others said you can try reinstalling Xampp or just try this.
if ($request->hasFile('image')) {
$file = $request->File('image');
$ext = $student->username.".".$file->clientExtension();
$ext->save('your_public_path/'.$ext);
//$path = public_path().'/images/';
//$file->move($path,$ext);
$student->image = $ext;
}
Example code from one of my project for your info
$image = $request->file('uploadUserAvatar');
$fileName = time().'.'.request()->uploadUserAvatar->getClientOriginalExtension() ;
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300,300);
$image_resize->save(('assets/img/user_avatars/'.$fileName));

laravel image upload error

i'm using intervention package to upload images with laravel and all things are fine from creating to saving image but the problem in the image column in database it stores this name with path
/private/var/folders/18/0w78rt691m99y_kv8xln4n0c0000gn/T/phpFkP3Gh
this is my code:
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
\Image::make($image)->save($location);
}
and this is the image name stored in images file 1503847676.jpg
please help me to find, where is the problem?
this is my whole method
public function update(Request $request, $id)
{
// Validating fields requests
$this->validate($request, [
'title' => 'required|min:6',
'subtitle' => 'required|min:6',
'slug' => 'required',
'body' => 'required',
'image' => 'required|mimes:jpeg,png,jpg,gif,svg'
]);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
\Image::make($image)->save($location);
}
//find target post
$post = Post::find($id);
//create upadeted data from inputs fields
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->image = $filename;
$post->slug = $request->slug;
$post->image = $request->image;
$post->status = $request->status;
$post->body = $request->body;
//save the new data to database
$post->save();
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
return redirect('/admin/post');
}
You don't need Intervention package for simple image upload w/o any modifications like resize etc. Try this
if( $request->hasFile('image')) {
$image = $request->file('image');
$location = public_path(). '/images/';
$filename = time() . '.' . $image->getClientOriginalExtension();
$image->move($location, $filename);
}
//find target post
$post = Post::find($id);
$post->image = $filename;
//remaining code
$post->save();
You can try this if you use Intervention image
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalName();
$path = public_path('images/' . $filename);
Image::make($image->getRealPath())->save($path);
$post->image = 'images/' . $filename;
I had a similar error like yours, I solved it by using the following:
$file = Input::file('image');
$image->move($location, $file->getClientOriginalName());

fetch the uploaded image from database in laravel 5.1

I have my upload function like this. I can upload the image but i cannot view it the blade.
Controller
public function addProduct()
{
return view('product.add_product');
}
public function saveProduct(Request $request)
{
$details = Input::all();
$product_validation = new Product;
$validation = Validator::make($details,$product_validation->setRules());
$destinationPath = '';
$filename = '';
if (Input::hasFile('image')) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
}
if($validation->fails())
return Redirect::to('/add_product')->withInput()->withErrors($validation);
else
{
$product = new Product;
$product->product_name = $details['product_name'];
$product->product_description = $details['product_description'];
$product->price = $details['price'];
$product->image = $destinationPath . $filename;
$product->date_uploaded = $details['date_uploaded'];
$product->save();
}
return view('product.add_product');
}
And here's my view
<img src="{{ asset('img/$details->image') }}" alt="{{ $details->product_name }}">
{!! $details->product_name !!}</h2>
{!! $details->price !!}
I know that my image fetching didn't work but how can i do the right code? Hope you can help me guys. Thank you in advance. ^_^
If you are storing you images in your public directory and simply want to return them in your view, I would suggest using $product->image to store the relative path to the file.
i.e. $product->image = '/path/to/folder' . $filename;
You can then simply do this in your blade template by passing $product to the view
Controller
return view('product.add_product', [
'product' => $product,
]);
Blade View
<img src="{{ $product->image }}">

PHP - Resize image on upload AND keep original

I'm creating a site using Laravel 4, which allows an admin to upload a large number of images at a time. Currently, I'm able to do just that, where each image is given its own unique ID and put into its own folder named with the same ID.
The problem is that I need the application to also upload a second, resized (smaller) version of the image along with the original. I learned that you must resize an image on the client side, so I'm not sure how I would go about saving the original image, as well as smaller version. The smaller image should be named using the same ID, with some sort of identifier like "-smaller" at the end of the name.
Here's my current front end;
{{ Form::open(array('url' => 'imageUpload', 'files' => true, 'method' => 'post'))}}
<div class="form-group">
<label for="fileToUpload" class="col-sm-2 control-label">Choose All Images</label>
</br>
{{ Form::file('images[]', ['multiple' => true]) }}
</div>
<div class="col-sm-offset-2 col-sm-10">
{{ Form::submit('Add Photos', ['class' => 'btn btn-large btn-primary openbutton'])}}
<!--<button type="submit" class="btn btn-default">Sign in</button> -->
</div>
{{ Form::close() }}
And here's my controller;
$files = Input::file('images');
foreach($files as $file) {
$rules = array(
'file' => 'required|mimes:png,gif,jpeg,txt,pdf,doc,rtf|max:9999999999'
);
$validator = \Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$id = Str::random(14);
$id = $race . "-" . $id;
$destinationPath = 'raceImages/' . $id;
//$filename = $id;
$filename = $file->getClientOriginalName();
$mime_type = $file->getMimeType();
$extension = $file->getClientOriginalExtension();
$upload_success = $file->move($destinationPath, $id);
);
} else {
return Redirect::back()->with('error', 'I only accept images.');
}
}
This is how I resolved the same problem in my app:
Install this package: https://github.com/Intervention/image
Use this code:
$createnew = new Yourmodelname;
$avatar = Input::file('pic_path');
if (isset($avatar)) { //will process the code only if an image was properly pointed in the form
$image = Input::file('pic_path');
var_dump($image->getRealPath()); // just for error tracking
$filename = $image->getClientOriginalName();
if (Image::make($image->getRealPath())->save('foldername/yourprefix_' . $LastInsertId . '_' . $filename)) { } // foldername is related to your public folder
if (Image::make($image->getRealPath())->widen(200)->save('foldername/thumbs/thumb_yourprefix_' . $LastInsertId . '_' . $filename)) {
}
$createnew->pic_path = 'event_poster_' . $LastInsertId . '_' . $filename;
$createnew->pic_thumb = 'event_poster_thumb_' . $LastInsertId . '_' . $filename;
$createnew->save();
}
Now you have two files: one original (no changes) and a thumbnail scaled proportionally to width 280.
Other resize options you can find in the Intervention docs.

Image Upload / Laravel stores image as a .tmp and not .img file

I created a Forum which should upload an image.
In my form i`ve
{{ Form::file('image') }}
This is a part of my controller:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Post::$rules);
if ($v->passes()) {
$post = new Post;
$post->title = Input::get('title');
$post->body = Input::get('body');
$post->image = Input::file('image'); // your file upload input field in the form should be named 'file'
$destinationPath = 'uploads/'.str_random(8);
$filename = $post->image->getClientOriginalName();
$extension =$post->image->getClientOriginalExtension(); //if you need extension of the file
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
$post->m_keyw = Input::get('m_keyw');
$post->m_desc = Input::get('m_desc');
$post->slug = Str::slug(Input::get('title'));
$post->user_id = Auth::user()->id;
$post->save();
return Redirect::route('posts.index');
}
return Redirect::back()->withErrors($v);
}
But laravel stores the image as a .tmp file in my database.
The path in my database is then "/uploads/xxxxx.tmp"
Why does laravel stores the image as .tmp and not as .img ?
What do i wrong and why does laravel stores the image as a .tmp file ?
The problem is in this line
$post->image = Input::file('image');
You assign the .temp image file to your model instance and that's what is stored in the database.
You can do it this way.
$post = new Post;
$post->title = Input::get('title');
$post->body = Input::get('body');
$file = Input::file('image');
$filename = $file->getClientOriginalName();
$destinationPath = 'uploads/'.str_random(8);
// This will store only the filename. Update with full path if you like
$post->image = $filename;
$uploadSuccess = $file->move($destinationPath, $filename);
I solved this problem by deleting the 'image' column in my $fillable variable. In Model Post.php
protected $table = "posts";
protected $fillable = [
'title',
'image', //delete if exists
'content'
];
.tmp file is the file which you select from your local computer. So you need to assign correct path to your model to store it with correct URL.

Categories