i am trying to update the image of profil ,because to user at the beginning it creates account without image, after it goes the update, so i store the image in root /aswakfolder/public/storage/profiles and i insert image link in db profiles/nameimage.jpeg, i created a function in helpers.php file to display the image its work very will, the problem here is that I do not understand the helpers function, and it does not meet my needs, my need is when image upload and exists it displays my image if not it displays image not-found.jpeg,in my case it always displays not-found.jpeg.
stock image in my folder, and url image insert in db very well.
UsersController.php
public function update(Request $request, $id)
{
$user=User::find($id);
if($request->hasFile('image'))
{
$image = $request->file('image');
$path = $request->image->store('profiles');
$user->image = $path;
}
$request->image = $user->image;
$user->id = Auth::user()->id;
$user->update([
$user->name => $request->name,
$user->email => $request->email,
$user->telephone => $request->telephone,
$user->daten => $request->daten,
$user->country_id=> $request->country_id,
$user->state_id => $request->state_id,
$user->city_id => $request->city_id,
$user->image => $request->image,
]);
session()->flash('success', 'user updated successfully !!');
return redirect('users');
}
helpers.php
function productImage($path)
{
return $path && file_exists('/aswakfolder/public/storage/'.$path) ? asset('/aswakfolder/public/storage/'.$path) : asset('/aswakfolder/public/storage/not-found.jpg');
}
index.blade.php
<div class="inner" style="background-image: url({{ asset(productImage($users->image)) }})">
Make sure you run the commend php artisan storage:link to create the shortcurt on public/ folder.
Documentation
Related
I am making a web application in the Laravel Framework. I have written code that saves a image in the database.
Code for saving a image in the database (code in my controller):
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'category_id' => 'required',
]);
$user = request()->user();
$assortment = $user->assortments()->create($request->all());
if($request->hasFile('image') && $request->file('image')->isValid()) {
if($request->hasFile('image') && $request->file('image')->isValid()) {
//dd($request->image->store('images', 'public'));
$assortment->image_path = $request->image->store('images', 'public');
$assortment->save();
//Check what the Storage::url() generates
//dd(Storage::disk('public')->url($assortment->fresh()->image_path));
}
else {
abort(500, "Image not valid");
}
}
if ($request->wantsJson()) {
return response([], 204);
}
return redirect()->route('assortments.show', $assortment->slug)
->with('success','Verzameling is succesvol aangemaakt.');
}
I want my image to be retrieved from my database in the view but I do not know how to go about doing this. I tried things like:
<img src="/images/{{ $imageVariableName }}"> Variables and path are changed
The view I am trying to make my image be retrieved and shown:
<div class="mt-10">
<ul class="md:grid md:grid-cols-2 md:gap-x-8 md:gap-y-10">
#foreach ($assortment->itemCategories as $category)
<li>
<a href="{{ route('categories.show', [$assortment->slug, $category->id]) }}">
<div class="flex px-4 py-5 bg-white shadow overflow-hidden sm:rounded-md sm:px-6">
<div class="flex-shrink-0">
<div class="flex items-center justify-center h-12 w-12 rounded-md bg-indigo-500 text-white">
<!-- Heroicon name: globe-alt -->
</div>
</div>
<div class="ml-4">
<h4 class="text-lg leading-6 font-medium text-gray-900">{{ $category->name }}</h4>
</div>
</div>
</a>
</li>
#endforeach
</ul>
</div>
Anyone know how I go about doing this?
EDIT
I also tried:
<img src="{{ Storage::disk('public')->url($assortment->image_path) }}">
But it also returned no image. Just returned:
I inspected the image and it returned the following link:
http://localhost/storage/tmp/phpSX2W3G
EDIT
I know now the problem has to do with my upload controller. The file should not be stored at a temporary path: /storage//tmp/phpL1ZVcx
EDIT 2
The storage link appears to be broken. Get this in my public/storage:
Greetings,
Parsa
you can use
<img src={{Storage::url($assortment->img)}} />
EDIT:
I found out your problem, the problem not in the display but actually in your upload code
if ($request->hasFile('image')) {
$image = $request->file('image'); //request the file
$fileName = md5($image->getClientOriginalName() . microtime()) . '.' . $image->getClientOriginalExtension(); //use md5 for security reasons and get the extension.
$image->storeAs('', $fileName, 'public'); //store the file in the public folder disk.
$assortment->image_path = $fileName;
$assortment->save();
}
should become, because $filename just a temporary upload file it will be delete later, the actual upload path will be return by storeAs
if ($request->hasFile('image')) {
$image = $request->file('image'); //request the file
$fileName = md5($image->getClientOriginalName() . microtime()) . '.' . $image->getClientOriginalExtension(); //use md5 for security reasons and get the extension.
$assortment->image_path = $image->storeAs('', $fileName, 'public'); //store the file in the public folder disk.
$assortment->save();
}
EDIT2: if you are using nginx you need to remove these line
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
}
You can try the below:
Have included comments in the code with dd() statements to debug - uncomment the dd() statements if you don't get it working to check.
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required',
'description' => 'required',
'category_id' => 'required',
]);
$user = request()->user();
if(!$user) {
abort(401, 'Unauthenticated');
}
$assortment = $user->assortments()->create($validated);
if($request->hasFile('image') && $request->file('image')->isValid()) {
//dd($request->image->store('images', 'public'));
$assortment->image_path = $request->image->store('images', 'public');
$assortment->save();
//Check what the Storage::url() generates
//dd(Storage::disk('public')->url($assortment->fresh()->image_path));
} else {
abort(422, "Image not valid");
}
if ($request->wantsJson()) {
return response([], 204);
}
return redirect()->route('assortments.show', $assortment->slug)
->with('success','Verzameling is succesvol aangemaakt.');
}
Verify that you have a public disk configured in the config\filesystems.php, something like
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'public',
],
//And links specified for symlinking when php artisan storage:link is run
'links' => [
public_path('storage') => storage_path('app/public'),
],
Then run
php artisan storage:link
and check in the public folder that there exists a symlinked storage folder
Then in your blade view, you can use
<img src="{{ Storage::disk('public')->url($assortment->image_path) }}" />
//OR
<img src="/storage/{{ $assortment->image_path }}" />
Controller:
if ($request->hasFile('image')) {
$image = $request->file('image');
$assortment->image_path = $image->store('', 'public');
$assortment->save();
}
NB: Laravel by default will create a unique name for a file and manage extension for you - dependent on your use case you may not need to make this filename yourself.
Artisan Command
php artisan storage:link
Generates the correct symlinks for your public storage.
Template
{{ Storage::url($assortment->image_path) }}
Those three things together should work.
Try
<img src="{{ url('storage/images/'.$assortment->image_path) }}"/>
Try a much simplified version:
if ($request->hasFile('image')) {
$path = $request->file('image')->storePublicly('images'); // Store file in public disk & return path
$assortment->image_path = $path; // If you want filename only, use basename($path)
$assortment->save();
}
After that, you can use Storage::disk('public')->url($assortment->image_path) in your view. Using getClientOriginalExtension() and getClientOriginalExtension() probably isn't a good idea since it's not considered a safe value (source). Laravel's store method saves the file and returns the hashed filename with path for you so you don't have to worry about all that :)
Make sure storage symlink is created:
php artisan storage:link
Also make sure post_max_size and upload_max_filesize in your php.ini are set with sufficient amount.
I want to display an image on my website that i uploaded.
In my database the image is store in local/temp/ i don't know why.
I'm getting a 404 not found error when I want to access to the image
http://projet-site-e-commerceb2.test/storage/uploads/cL9pMFrZO92vliCKvlSgCq64TZOvnG3C2uzxgl6r.jpeg
I did php artisan storage:link to put the storage folder to remain public.
After i uploaded an image, i can see it in public/storage/uploads
HTML
<img src="{{ asset('/storage/' . $product->image)}}" style="height:200" class="card-img-top">
ProdcuctControllerController
public function store(Request $request)
{
$inputs = $request->except('_token');
$product = new Product();
$this->storeImage($product);
foreach ($inputs as $key => $value) {
$product->$key = $value;
}
$product->save();
return redirect('admin/gamelist');
}
public function storeImage($product)
{
if (request()->has('image')){
$product->update([
'image' => request()->image->store('updloads', 'public'),
]);
}
}
//Here is my edit form (image field)
I have an edit form which has an image field where a user can upload a new image if he wants to.
But if the user does not upload a new photo I want to just use the photo that's already in the database. And not update the image field at all. But in my code whenever I am trying to without uploading new image form is not taking the old input value.
<div class="form-group">
<input type="file" name="image">
</div>
//this is the update function
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required',
'image' => 'mimes:jpeg,bmp,png,jpg'
]);
// get form image
$image = $request->file('image');
$slug = str_slug($request->name);
$category = Category::find($id);
if (isset($image))
{
// make unique name for image
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'.uniqid().'.'.$image->getClientOriginalExtension();
// check category dir is exists
if (!Storage::disk('public')->exists('category'))
{
Storage::disk('public')->makeDirectory('category');
}
// delete old image
if (Storage::disk('public')->exists('category/'.$category->image))
{
Storage::disk('public')->delete('category/'.$category->image);
}
// resize image for category and upload
$categoryimage = Image::make($image)->resize(1600,479)->stream();
Storage::disk('public')->put('category/'.$imagename,$categoryimage);
// check category slider dir is exists
if (!Storage::disk('public')->exists('category/slider'))
{
Storage::disk('public')->makeDirectory('category/slider');
}
// delete old slider image
if (Storage::disk('public')->exists('category/slider/'.$category->image))
{
Storage::disk('public')->delete('category/slider/'.$category->image);
}
// resize image for category slider and upload
$slider = Image::make($image)->resize(500,333)->stream();
Storage::disk('public')->put('category/slider/'.$imagename,$slider);
} else {
$imagename = $category->image;
}
$category->name = $request->name;
$category->slug = $slug;
$category->image = $imagename;
$category->save();
Toastr::success('Category Successfully Updated :)' ,'Success');
return redirect()->route('admin.category.index');
}
// When i click on the edit button it shows the No file Chosen it is not displaying the old image ..
you should change your validation
in STORE function, you should give an image and upload it (if it is required)
but in UPDATE function maybe the user does'nt want to change image and user only wants to change for exmaple just the name, so user can select no image in update
so your validation in UPDATE must be NULLABLE.
$this->validate($request,[
'name' => 'required',
'image' => 'nullable|mimes:jpeg,bmp,png,jpg'
]);
I've saved images of posts in different sub-folders inside public/images like featured_image (public/images/featured_image), banner(public/images/banner). I want to delete images(featured_image and banner) related to post when banner is deleted.
This is my setup in filesystem.php
'local' => [
'driver' => 'local',
'root' => public_path('images/'),
],
I'm trying this to delete posts and images related to this:
public function destroy($id)
{
//
$tour = Tour::find($id);
$tour->country()->detach();
Storage::delete('featured_image/$tour->featured_image');
Storage::delete('banner/$tour->banner');
$tour->delete();
Session::flash('success', 'The tour is sucessfully deleted.');
return redirect()->route('tours.index');
}
The post gets deleted successfully but the images are not deleted from the folder. Please suggest the possible solution.
It should be
Storage::delete('images/featured_image/' . $tour->featured_image);
Storage::delete('images/banner/' . $tour->banner);
If that doesn't work... you can also do.
$images = [
'featured_image' => public_path('images/featured_image/' . $tour->featured_image),
'banner_image' => public_path('images/banner/' . $tour->banner),
];
foreach($images as $image) {
if(file_exists($image)) {
unlink($image);
}
}
I got this working by using File:delete(); method.
public function destroy($id)
{
$tour = Tour::find($id);
$tour->country()->detach();
File::delete(public_path('/images/featured_image/' . $tour->featured_image));
File::delete(public_path('/images/banner/' . $tour->banner));
$tour->delete();
Session::flash('success', 'The tour is sucessfully deleted.');
return redirect()->route('tours.index');
}
I'm trying to learn to an process image form that uploads images to a database and lets users view the image on the website, this is done using Laravel 4. I must have some sort of bug, because the view doesn't have any errors, but when I select an image to upload and hit the "save" button on my form, nothing happens other than it looks like the form has been refreshed because the file is gone.
Routes
// This is for the get event of the index page
Route::get('/', array(
'as' => 'index_page',
'uses' => 'ImageController#getIndex'
));
// This is for the post event of the index page
Route::post('/', array(
'as' => 'index_page_post',
'before' => 'csrf',
'uses' => 'ImageController#postIndex'
));
ImageController.php
class ImageController extends BaseController {
public function getIndex()
{
// Let's first load the form view
return View::make('tpl.index');
}
public function postIndex()
{
// Let's validate the form first with the rules which are set at the model
$input = Input::all();
$rules = Photo::$upload_rules;
$validation = Validator::make($input, $rules);
// If the validation fails, we redirect the user to the index page, with errors
if ($validation->passes()) {
// If the validation passes, we upload the image to the database and process it
$image = Input::file('image');
// This is the original uploaded client name of the image
$filename = $image->getClientOriginalName();
// Because Symfony API does not provide filename
// without extension, we will be using raw PHP here
$filename = pathinfo($filename, PATHINFO_FILENAME);
// We should salt and make an url-friendly version of the file
$fullname = Str::slug(Str::random(8) . $filename) . '.' .
$image->getClientOriginalExtension();
// We upload the image first to the upload folder, then
// get make a thumbnail from the uploaded image
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
// If the file is now uploaded we show a success message
// otherwise, we show an error
if ($upload) {
// image is now uploaded, we first need to add column to the database
$insert_id = DB::table('photos')->insertGetId(
array(
'title' => Input::get('title'),
'image' => $fullname
)
);
// Now we redirect to the image's permalink
return Redirect::to(URL::to('snatch/'.$insert_id))
->with('success', 'Your image is uploaded successfully!');
}
else {
// Image cannot be uploaded
return Redirect::to('/')->withInput()
->with('error', 'Sorry, the image could not be uploaded.');
}
}
else {
return Redirect::to('/')
->withInput()
->withErrors($validation);
}
}
Image Model
class Photo extends Eloquent {
// the variable that sets the table name
protected $table = 'photos';
// the variable that sets the table name
protected $fillable = array('title', 'image');
// the timestamps enabled
public $timestamps = true;
// Rules of the image upload form
public static $upload_rules = array(
'title' => 'required|min:3',
'image' => 'required|image'
);
}
The view for the form
#extends('frontend_master')
#section('content')
{{ Form::open(array('url' => '/', 'files' => true )) }}
{{ Form::text('title', '', array(
'placeholder' => 'Please insert your title here')) }}
{{ Form::file('image') }}
{{ Form::submit('save', array('name' => 'send')) }}
{{ Form::close() }}
#stop
Let me know if you can find any bugs, I'm pretty sure something must be going wrong in my ImageController#postIndex
Thanks for any insights
2 things you need to check out.
1st off, once you updated your composer.json to include the Intervention/Image package. you should run composer dump-autoload to refresh the autoload file.
2ndly, there's a logical error in your controller.
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
should be
Image::make(Config::get('image.image_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
because you've already moved the image file to image_folder with the code below:
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Hope this helps.