Detecting file presence in Laravel 5

Purpose . If the file exists, upload the file, otherwise upload default.png.


I 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 my default image , while I am 100% sure that it 1002.pngexists.

How to check if this file exists?

+11
source share
6 answers

Decision

      @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
+10
source

Wherever you can, try to reduce the number of operators if. 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 for this method to verify your statement :-)

+36

, "::"

$result = File::exists($myfile);
+16

Laravel 5.5 exists :

https://laravel.com/docs/5.5/filesystem

$exists = Storage::disk('s3')->exists('file.jpg');

:

$file = ($exists) ? Storage::disk('s3')->get('file.jpg') : 
         Storage::disk('s3')->get('default.jpg');
+5
@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

, , '/'

 @if(file_exists('uploads/users-pic/'.auth()->user()->code_melli.'.jpg'))
+4

.

<?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
+1

Source: https://habr.com/ru/post/1618167/


All Articles