如何在 yajra 数据表 laravel 8 的 html 中隐藏描述列但在导出 CSV 中显示

Posted

技术标签:

【中文标题】如何在 yajra 数据表 laravel 8 的 html 中隐藏描述列但在导出 CSV 中显示【英文标题】:How to hide description column in html of yajra datatable laravel 8 but show in export CSV 【发布时间】:2022-01-02 12:34:15 【问题描述】:

我现在在表中有 id、pro_id、user_name、电子邮件、电话、金额和描述字段我想导出 CSV 文件中的所有列,所以我在数据表中创建所有列 但如果描述太长,那么在表格中不适合展示 现在我要做的是在 HTML 视图中隐藏描述列,但我想将其列导出到 CSV 文件中。

我的项目在 laravel-8 中,我正在使用 yajra datable-8

数据文件

namespace App\DataTables;

use App\Library\Projectfunction;
use App\Models\PropertyOffer;
use App\Models\Property;
use Yajra\DataTables\html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use DB;

class PropertyOfferDataTable extends DataTable 
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query) 
        
        return datatables()
            ->eloquent($query)
            ->addColumn('action', 'admin.offer.action')->setRowId('id')
            ->filterColumn('address',function ($query, $keyword)
                $query->whereRaw(DB::getTablePrefix()."properties.address  like ?", ["%$keyword%"]);
            )
            ->filterColumn('state',function ($query, $keyword)
                $query->whereRaw(DB::getTablePrefix()."states.name  like ?", ["%$keyword%"]);
            )            
            ->addIndexColumn();
        
    

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\PropertyOffer $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(PropertyOffer $model)
    
        return $model->newQuery()
                ->select(['property_offers.id','property_offers.user_name','property_offers.email','property_offers.phone','property_offers.amount','property_offers.description','property_offers.created_at','properties.address', 'states.name as state' ])
                ->leftJoin('properties', 'property_offers.pro_id', '=', 'properties.id')
                ->leftJoin('states', 'states.id', '=', 'properties.state_id')
                ->whereBetween('property_offers.created_at', [$this->from, $this->to])
                ->orderBy('created_at', 'desc');
    

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    
        return $this->builder()
                    ->setTableId('property-offer-table')
                    ->columns($this->getColumns())
                    ->addColumnBefore(Projectfunction::indexColumn())
                    ->minifiedAjax()
                    ->addAction()
                    ->dom('Blfrtip')
                    ->orderBy(0,'desc')
                    ->buttons(
                        Button::make('csv')->addClass('btn btn-success mx-2'),
                        //Button::make('reset')->addClass('mx-1 btn btn-danger')
                    );
    

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    
        return [
            Column::make('address')->title('Property')->width("15%"),
            Column::make('state')->title('State'),
            Column::make('user_name')->title('Name'),
            Column::make('email'),
            Column::make('phone'),
            Column::make('amount')->title('Amount'),
            Column::make('description')->title('Description'),
            Column::make('created_at')->title('Date'),
        ];
    

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    
        return 'PropertyOffer_' . date('YmdHis');
    

控制器文件

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\DataTables\PropertyOfferDataTable;
use App\Library\Globalfunction;
use App\Models\PropertyOffer;
use Carbon\Carbon;
use Illuminate\Support\Facades\Input;


class PropertyOfferController extends Controller 
    
    function __construct() 
        $this->PropertyOffer = New PropertyOffer();
    
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(PropertyOfferDataTable $dataTable, Request $request) 
        
        $formData = $request->all();  
        
        if((isset($formData['from_date']) && !empty($formData['from_date']))):
            $date = strtr($formData['from_date'], '/', '-');;
            $from_date = date('Y-m-d', strtotime($date));;
        else:
            $from_date = date('2021-01-01');        
        endif;
        if((isset($formData['to_date']) && !empty($formData['to_date']))):
            $date = strtr($formData['to_date'], '/', '-');;
            $to_date = date('Y-m-d', strtotime($date));;
        else:
            $to_date = Carbon::now();        
        endif;
               
        return $dataTable->with([
                'from' => $from_date,
                'to' => $to_date,
            ])->render('admin.offer.listing');
        
    

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    
        //
    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    
        //
    

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    
        //
    

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    
        $action = 'edit';
        $html = $this->PropertyOffer->getPageHTML($id,$action);
        $formParam = array('actionUrl'=>route('admin.offer.update',$id),'cancelUrl'=>route('admin.offer.index'),'sbtName'=>'btnpage','action'=>$action);
        $htmlContent = Globalfunction::getAdminFormHTML(ucfirst($action).' Inquiry',$html,$formParam);
        return view('admin.inquiry.edit',compact('htmlContent'));
    

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    
        $pageContent=Globalfunction::get_contentFilter(str_replace(array("\r","\n","\r\n"),"",$request->description));

        $formData = ["user_name"=>$request->user_name,"email"=>$request->email,'phone'=>$request->phone,'amount'=>$request->amount,'description'=>$pageContent[0]];

        $PropertyOffer = PropertyOffer::find($id);
        $PropertyOffer->update($formData);

        session()->flash('success',__('Offer Updated successfully'));

        return redirect()->route('admin.offer.index');
    

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    
        PropertyOffer::find($id)->delete();
        return response()->json(['success'=>'Offer deleted successfully.']);
    


查看文件

@extends('layouts.admin.app')

@push('styles')
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    <link href=" asset('plugin/bootstrap-datepicker/bootstrap-datepicker.css') " rel="stylesheet">
    <link href=" asset('plugin/bootstrap-daterangepicker/bootstrap-daterangepicker.css') " rel="stylesheet">
@endpush

@section('content')
    <div class="card">
        
        <form method="get" action=" route('admin.offer.index') ">
            @csrf            
            <div class="row card-body">
                <div class="col-12 col-sm-12 col-md-8">
                    <div class="input-daterange input-group" id="datepicker-range">
                        <input type="text" class="form-control" name="from_date" id="from_date" value=" (isset($_GET['from_date']) && !empty($_GET['from_date'])) ? $_GET['from_date'] : '' " placeholder="From Date">
                        <div class="input-group-prepend">
                            <span class="input-group-text">to</span>
                        </div>
                        <input type="text" class="form-control" name="to_date" id="to_date" value=" (isset($_GET['to_date']) && !empty($_GET['to_date'])) ? $_GET['to_date'] : '' " placeholder="To Date">
                    </div>
                </div>
                <div class="col-12 col-sm-12 col-md-4">
                    <button type="submit"` class="dt-button buttons-csv btn btn-success mx-2" tabindex="0" aria-controls="property-inquiry-table"><span><i class="fa fa-search"></i> Search</span></button>
                    <a href=" route('admin.offer.index') " class="dt-button buttons-reset mx-1 btn btn-danger" tabindex="0" aria-controls="property-inquiry-table"><span><i class="fa fa-undo"></i> Reset</span></a>                
                </div>
            </div>
        </form>
        
        <div class="card-datatable table-responsive">
            !! $dataTable->table(['class'=>'table-bordered table table-striped'],false) !!
        </div>
        
    </div>
    !! $dataTable->scripts() !!
    @push('scripts')
        <script src=" asset('plugin/bootstrap-datepicker/bootstrap-datepicker.js') "></script>
        <script src=" asset('plugin/bootstrap-daterangepicker/bootstrap-daterangepicker.js') "></script>
        <script>
            let isRtl = $('html').attr('dir') === 'rtl';
            $('#datepicker-range').datepicker(
                clearBtn: true,
                format: "dd/mm/yyyy",
                orientation: isRtl ? 'auto right' : 'auto left'
            );
            function delRec(id)
                if(id>0 && confirm("Are You sure want to delete!"))
                    var tableId = $('table').attr('id');
                    var page_id = $(this).data("id");
                    $.ajax(
                        type: "DELETE",
                        url: " route('admin.offer.store') "+'/'+id,
                        success: function (data) 
                            window.LaravelDataTables[tableId].draw();
                        ,
                        error: function (data) 
                            console.log('Error:', data);
                        
                    );
                
            
        </script>
    @endpush
@endsection

【问题讨论】:

【参考方案1】:

您可以通过导出自定义列实现此目的

首先,您需要在数据表的文件中删除

Column::make('description')->title('Description'),

其次,需要添加自定义列的数组

protected $exportColumns = [
        ['data' => 'address', 'title' => 'Property'],
        ['data' => 'state', 'title' => 'State'],
        ['data' => 'user_name', 'title' => 'Name'],
        ['data' => 'email', 'title' => 'Email'],
        ['data' => 'phone', 'title' => 'Phone'],
        ['data' => 'amount', 'title' => 'Amount'],
        ['data' => 'description', 'title' => 'Description'],
        ['data' => 'created_at', 'title' => 'Date'],
    ];

您的所有数据表文件如下所示

namespace App\DataTables;

use App\Library\Projectfunction;
use App\Models\PropertyOffer;
use App\Models\Property;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use DB;

class PropertyOfferDataTable extends DataTable 
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query) 
        
        return datatables()
            ->eloquent($query)
            ->addColumn('action', 'admin.offer.action')->setRowId('id')
            ->filterColumn('address',function ($query, $keyword)
                $query->whereRaw(DB::getTablePrefix()."properties.address  like ?", ["%$keyword%"]);
            )
            ->filterColumn('state',function ($query, $keyword)
                $query->whereRaw(DB::getTablePrefix()."states.name  like ?", ["%$keyword%"]);
            )            
            ->addIndexColumn();
        
    

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\PropertyOffer $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(PropertyOffer $model)
    
        return $model->newQuery()
                ->select(['property_offers.id','property_offers.user_name','property_offers.email','property_offers.phone','property_offers.amount','property_offers.description','property_offers.created_at','properties.address', 'states.name as state' ])
                ->leftJoin('properties', 'property_offers.pro_id', '=', 'properties.id')
                ->leftJoin('states', 'states.id', '=', 'properties.state_id')
                ->whereBetween('property_offers.created_at', [$this->from, $this->to])
                ->orderBy('created_at', 'desc');
    

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    
        return $this->builder()
                    ->setTableId('property-offer-table')
                    ->columns($this->getColumns())
                    ->addColumnBefore(Projectfunction::indexColumn())
                    ->minifiedAjax()
                    ->addAction()
                    ->dom('Blfrtip')
                    ->orderBy(0,'desc')
                    ->buttons(
                        Button::make('csv')->addClass('btn btn-success mx-2'),
                        //Button::make('reset')->addClass('mx-1 btn btn-danger')
                    );
    

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    
        return [
            Column::make('address')->title('Property')->width("15%"),
            Column::make('state')->title('State'),
            Column::make('user_name')->title('Name'),
            Column::make('email'),
            Column::make('phone'),
            Column::make('amount')->title('Amount'),
            Column::make('created_at')->title('Date'),
        ];
    
    
    /**
     * Export Customized Columns.
     *
     * @return string
    */    
    protected $exportColumns = [
        ['data' => 'address', 'title' => 'Property'],
        ['data' => 'state', 'title' => 'State'],
        ['data' => 'user_name', 'title' => 'Name'],
        ['data' => 'email', 'title' => 'Email'],
        ['data' => 'phone', 'title' => 'Phone'],
        ['data' => 'amount', 'title' => 'Amount'],
        ['data' => 'description', 'title' => 'Description'],
        ['data' => 'created_at', 'title' => 'Date'],
    ];

    /**
     * Get filename for export.
     *
     * @return string
    */
    protected function filename()
    
        return 'PropertyOffer_' . date('YmdHis');
    

希望它能更好地帮助你。

【讨论】:

以上是关于如何在 yajra 数据表 laravel 8 的 html 中隐藏描述列但在导出 CSV 中显示的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 8 Yajra DataTable 在同一页面刷新

如何在 yajra 数据表 laravel 中添加操作列

如何在 Laravel 的一页上拥有多个 Yajra 数据表?

laravel 如何在 yajra 数据表中按创建日期排序

如何将数据库索引与 Datatables 和 yajra/laravel-datatables 一起使用

Laravel,Yajra Datatable,如果 y 那么如何返回 Yes else No