首页 > 解决方案 > 如何在 Laravel 7 导出中获取变量值?

问题描述

我正在尝试在 Status 列中获取 $status 值,所以我将如何使用下面的代码来获取它

public function collection() {

    if(Auth::user()->is_accepted == 1) {
        $status = 'Accepted';
    } elseif (Auth::user()->is_accepted == NULL) {
        $status = 'Waiting Confirmation';
    } else {
        $status = 'Rejected';
    }

    return Entrepreneur::select('name', 'contact', 'address', 'business_name', 'business_contact', 'business_address', 'is_accepted')->get();
}

public function headings(): array {
    return [
        'Name',
        'Contact',
        'Address',
        'Business Name',
        'Business Contact',
        'Business address',
        'Status'
    ];
}

标签: phpexcellaravelexport

解决方案


使用map()函数参考链接https://laravel.com/docs/7.x/collections#method-map
通过这个你可以向任何集合添加新键

public function collection()
    {
        $entrepreneur =  Entrepreneur::select('name', 'contact', 'address', 'business_name', 'business_contact', 'business_address')->get();
        $entrepreneur->map(function ($row) {
            if ($row['is_accepted'] == 1) {
                $status = 'Accepted';
            } elseif ($row['is_accepted'] == NULL) {
                $status = 'Waiting Confirmation';
            } else {
                $status = 'Rejected';
            }
            return $status;
        });
        return $entrepreneur;
    }

推荐阅读