如何检查Image是否存在,否则显示Laravel 5.2

时间:2016-02-02 21:16:47

标签: php oop laravel laravel-5.2

我需要检查用户可以上传的横幅是否存在动态填充的图像,如果用户没有上传横幅图片,那么我想显示其他内容,例如默认图片。

这是我展示的图片横幅。

@foreach ($flyer->bannerPhotos as $photo)
    <img src="/travel/{{ $photo->thumbnail_path }}" alt="{{ $flyer->owner->username }}" data-id="{{ $photo->id }}" id="Banner-image">
@endforeach

我尝试过“file_exists”,如果$ photo =='',则显示其他内容,但它不起作用。您是否知道如何做到这一点?

***********编辑************

TravelFlyerController.php(缩短)

<?php

namespace App\Http\Controllers;

use App\User;
use App\Flyer;
use App\FlyerPhoto;
use App\FlyerBanner;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\FlyerPhotoRequest;
use App\Http\Requests\FlyerBannerRequest;
use App\Http\Requests\TravelFlyersRequest;

class TravelFlyersController extends Controller {

    /**
     * Add banner photo to a flyer.
     *
     * @param $title
     * @param FlyerBannerRequest $request
     */
    public function addBannerPhoto($title, FlyerBannerRequest $request) {
        // create a new photo instance from a file upload
        $photo = FlyerBanner::fromFile($request->file('photo'))->upload();

        // Set Flyer::LocatedAt() in (Flyer.php Model)
        // = to the title, and add the banner photo.
        // -- Find the flyer and add the banner photo.
        Flyer::LocatedAt($title)->addBannerPhoto($photo);
    }

FlyerBanner.php模型:

<?php

namespace App;

use Image;
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpFoundation\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FlyerBanner extends Model {

    /**
     * @var string
     */
    protected $table = "flyer_banner";

    /**
     * @var array
     */
    protected $fillable = ['name', 'path', 'thumbnail_path'];

    /**
     * @var
     */
    protected $file;

    /**
     * @var
     */
    protected $name;


    /**
     * A banner photo belongs to a flyer.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function flyer() {
      return $this->belongsTo('App\Flyer');
    }


    /**
     * Make a new instance from an uploaded file.
     *
     * @param UploadedFile $file
     * @return static
     */
    public static function fromFile(UploadedFile $file) {
        // Make new instance of photo.
        $photo = new static;

        // Assign the Uploaded file to the $file object.
        $photo->file = $file;

        // Set $photo to the fill properties, which are
        // the name, path, and thumbnail path of a photo.
        $photo->fill([
            'name' => $photo->setFileName(),
            'path' => $photo->filePath(),
            'thumbnail_path' => $photo->thumbnailPath()
        ]);

        // return the photo
        return $photo;

    }


    /**
     * Get the banner photos base directory.
     */
    public function baseDir() {
        return 'src/public/FlyerBanner/photos';
    }


    /**
     * Get the name and extension of the banner photo.
     *
     * @return string
     */
    public function setFileName() {
        // Get the file name original name
        // and encrypt it with sha1
        $hash = sha1 (
            $this->file->getClientOriginalName()
        );

        // Get the extension of the photo.
        $extension = $this->file->getClientOriginalExtension();

        // Then set name = merge those together.
        return $this->name = "{$hash}.{$extension}";
    }



    /**
     *  Return the full file path of the banner photo, with the name.
     *
     * @return string
     */
    public function filePath() {
        return $this->baseDir() . '/' . $this->name;
        // Ex: 'BannerPhoto/photos/foo.jpg'
    }


    /**
     * Return the full file thumbnail path of the banner photo, with the name.
     *
     * @return string
     */
    public function thumbnailPath() {
        return $this->baseDir() . '/tn-' . $this->name;
        // Ex: 'BannerPhoto/photos/tn-foo.jpg'
    }


    /**
     * Upload the file to the proper directory.
     *
     * @return $this
     */
    public function upload() {
        // move a file to the base directory with the file name.
        $this->file->move($this->baseDir(), $this->name);

        // Make the thumbnail.
        $this->makeThumbnail();

        return $this;
    }


    /**
     * Function to make the actual thumbnail.
     * -- make and save reference the Image intervention library, not Eloquent. --
     */
    protected function makeThumbnail() {
        Image::make($this->filePath())
            ->fit(2000, 800)
            //->resize(null, 400, function ($constraint) {
             //   $constraint->aspectRatio();
             //   $constraint->upsize();
            //})
            ->save($this->thumbnailPath());
    }


    /**
     * Delete the banner photo path and thumbnail path in DB.
     * Access the delete function in FlyerController@destroyBannerPhoto method
     */
    public function delete() {

        $image = $this->path;
        $thumbnail_image = $this->thumbnail_path;

        \File::delete([
            $image,
            $thumbnail_image
        ]);

        parent::delete();
    }

}

宣传单照片横幅上传表格:

<form action="/travel/{{ $flyer->title }}/banner" method="post" class="dropzone" id="addBannerForm" enctype="multipart/form-data">
  {{ csrf_field() }}
</form>

我的路线:

Route::group(['middleware' => ['web']], function () {

    /** Resource Route For Travel Flyers */
    Route::resource('travelflyers', 'TravelFlyersController');

    /** Show a Flyer. **/
    Route::get('{title}', 'TravelFlyersController@show');

   

    /** Add a photo banner to a flyer **/
    Route::post('{title}/banner', 'TravelFlyersController@addBannerPhoto');

    /** Delete Flyer Banner photo **/
    Route::delete('photo/{id}', [
        'uses' => '\App\Http\Controllers\TravelFlyersController@destroyBannerPhoto',
        'as'   => 'flyer.delete.banner',
    ]);

});

4 个答案:

答案 0 :(得分:2)

Blade也有一个默认的is_null简写,您也可以使用<img src="travel/{{ $photo->thumbnail_path or 'path/to/default.jpg'}}" >

答案 1 :(得分:2)

在一个简单的行

File::exists($imagePath)?true:false;
  • 这是用来: \照亮\文件系统\文件系统

  • 记得添加命名空间:

    使用文件;

答案 2 :(得分:1)

在你的模型中你应该能够做到这一点;

public function getThumbnailPathAttribute($val){
    return is_null($val)?"default/path.png":$val;
}

答案 3 :(得分:0)

如果您的Photo模型与FlyerbannerPhotos关系,则可以在Photo模型中添加以下访问者:

public function getLocationAttribute($val) {
   if ($this->thumbnail_path) {
         return '/travel/'. $this->thumbnail_path;
   }
   return '/some/other/location/with/default/photo.jpg');
}

现在在您的Blade文件中,您可以执行以下操作:

@foreach ($flyer->bannerPhotos as $photo)
    <img src="{{ $photo->location }}" alt="{{ $flyer->owner->username }}" data-id="{{ $photo->id }}" id="Banner-image">
@endforeach