Goal : If the file exist, load the file, else load the default.png
.
I've tried
@if(file_exists(public_path().'/images/photos/account/{{Auth::user()->account_id}}.png'))
<img src="/images/photos/account/{{Auth::user()->account_id}}.png" alt="">
@else
<img src="/images/photos/account/default.png" alt="">
@endif
Result
It kept load my default image while I'm 100% sure that 1002.png
is exist.
How do I properly check if that file is exist ?
Wherever you can, try and reduce the number of if
statements. For example, I would do the following:
// User Model
public function photo()
{
if (file_exists( public_path() . '/images/photos/account/' . $this->->account_id . '.png')) {
return '/images/photos/account/' . $this->account_id .'.png';
} else {
return '/images/photos/account/default.png';
}
}
// Blade Template
<img src="{!! Auth::user()->photo() !!}" alt="">
Makes your template cleaner and uses less code. You can also write a unit test on this method to test your statement as well :-)
Check if file exists on action with "File::" and pass the resut to the view
$result = File::exists($myfile);
Solution
@if(file_exists( public_path().'/images/photos/account/'.Auth::user()->account_id.'.png' ))
<img src="/images/photos/account/{{Auth::user()->account_id}}.png" alt="">
@else
<img src="/images/photos/account/default.png" alt="">
@endif
@if(file_exists('uploads/users-pic/'.auth()->user()->code_melli.'.jpg'))
<img src="{{'/uploads/users-pic/'.auth()->user()->code_melli.'.jpg'}}"
class="img-circle" alt="{{auth()->user()->name}}" width="60" height="60">
@else
<img src="/assets/images/user-4.png" width="60" height="60" class="img-circle img-corona" alt="user-pic" />
@endif
as you can see in above code when you want to check image don't use '/' at the first of you path
@if(file_exists('uploads/users-pic/'.auth()->user()->code_melli.'.jpg'))
Save the of the file in the database.If the image path exist
<?php
$path = "packages/pathoffile/img/media/" . $filename;
$media = isset($media) ? $media : ""; //If media is saved
?>
@if($media == "")
<img src='../packages/defaultimagelocation/assets/img/user.png' />
@else
<img src='../packages/originalmedialocation/img/media{{ $media }}' />
@endif
In Laravel 5.5, you can use the exists
method on the storage facade:
https://laravel.com/docs/5.5/filesystem
$exists = Storage::disk('s3')->exists('file.jpg');
You could use a ternary expression:
$file = ($exists) ? Storage::disk('s3')->get('file.jpg') :
Storage::disk('s3')->get('default.jpg');