fetch the uploaded image from database in laravel 5.1 - php

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 }}">

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));

How to display image after file upload problem with laravel

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'
]);
}

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());

How to display uploaded image with php laravel

How can I display uploaded image from stored location and I want to carry over the same image name to
<input id = "Picture" type="file" name="Picture" accept="image/*" />
This code is used in Controller.php when upload
$img = $input['Picture'];
$name = $img->getClientOriginalName();
$uploaded = $img->move('public/img', $name);
This is where uploaded image will show in my new.blade.php
<img src="#" id="Image" name="Image" />
And Image name doesn't save original name to mysql, it saved like C:xampp mpphpB7CF.tmp
How can I do to save original name that I Uploaded.
Check below code this is working code.
$file = $request->file('Picture');
$destinationPath = 'public/img/';
$originalFile = $file->getClientOriginalName();
$file->move($destinationPath, $originalFile);
This line $originalFile = $file->getClientOriginalName(); will assign original file name to $originalFile and use this variable name where you insert image in database.
Add below line to display image you have uploaded.
<img src='{{ asset('img/'.$originalFile) }}'>
$path = '';
if ($request->hasFile('Picture')) {
$file = $request->file('Picture');
$path = $file->storeAs(public_path('img'), $imageName);
//or
if (file_put_contents(public_path(img) . $imageName, $file)) {
$path = public_path(img) . $imageName;
}
}
return view('your-view', ['img_path' => $path]);;
and in your new.blade.php
<img src="{{ $img_path }}" id="Image" name="Image" />
In Controller
public function show($name)
{
$extension = File::extension($name);
$path = public_path('storage/' . $name);
if (!File::exists($path)) {abort(404);}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
Route
Route::get('/images/{name}', 'FileController#show');
Index.blade.php
<a href='{{ asset("images/$hire_details->file") }}'>click here to view image</a>
Return path from controller and display :
<img src='{{ asset('img/'.$name) }}'>
Return your $uploaded from controller to view
return view('new',['uploaded'=>$uploaded]);
and then in your view
<img src='{{ asset($uploaded) }}' >
I think you can try this:
use Input;
use Image;
$file = Input::file('Picture');
$imageName = $file->getClientOriginalName();
$imgUpload = Image::make($file)->save(public_path('img/' . $imageName));
<img src="{{ asset('img/'.$imageName) }}">
Note: If you have get error for Image then install package for Image from this link

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