【问题标题】:Laravel download only if field is not emptyLaravel 仅在字段不为空时下载
【发布时间】:2017-12-21 19:22:00
【问题描述】:

我有一个名为“ical”的字段,其中包含一个 url,但我想做的是运行一个函数,使用该 url 下载文件,但是当字段为空时忽略该行。目前它会为每一行下载一个文件,如果有一个 url,它会填充正确的数据,但是当字段为空时,它会下载一个文件,但当然它是空的,而我只想完全如果为空则忽略该行。

代码如下:

<?php

namespace App\Console\Commands;

use App\Entity;
use Illuminate\Console\Command;
use Ixudra\Curl\Facades\Curl;

class DownloadIcal extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ical:download';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Download all ICAL files from ical field in businesses database';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $entities = Entity::pluck('ical', 'id');
        foreach ( $entities as $entityID => $entityIcal ) {
            $response = Curl::to($entityIcal)
                ->download('public/ical/'.$entityID.'.ics');
                $this->info("ICal Retrieved");
        }
    }
}

【问题讨论】:

  • 试试这个foreach ( $entities as $entityID =&gt; $entityIcal ) { if( $entityIcal ){ $response = Curl::to($entityIcal) -&gt;download('public/ical/'.$entityID.'.ics'); $this-&gt;info("ICal Retrieved"); } } !!

标签: php laravel curl laravel-5


【解决方案1】:

您所要做的就是在循环中使用if 并检查值是空还是空。

$entities = Entity::pluck('ical', 'id');

foreach ( $entities as $entityID => $entityIcal ) 
{
    if ( !is_null($entityIcal) and !empty($entityIcal))
    {
        $response = Curl::to($entityIcal)
        ->download('public/ical/'.$entityID.'.ics');
        $this->info("ICal Retrieved");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 2020-03-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多