How to add action columns in yajra datatables laravel

6.2k views Asked by At

im stuck adding column actions for edit and delete button with yajra datatables, im using DataTables Service because im wanna add export button too, here is my my datatables code :

public function dataTable($query)
{
    return datatables()
        ->eloquent($query);
}

/**
 * Get query source of dataTable.
 *
 * @param \App\InfoDataTable $model
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function query(InfoDataTable $model)
{
    // return $model->newQuery();
    $data = DataInfo::select('data-info.*');
    return $this->applyScopes($data);
}

/**
 * Optional method if you want to use html builder.
 *
 * @return \Yajra\DataTables\Html\Builder
 */


public function html()
{
  return $this->builder()
             ->columns($this->getColumns())
             ->addAction()
             ->parameters([
                 'dom' => 'Bfrtip',
                 'buttons' => ['csv', 'excel', 'print'],
             ]);
}

/**
 * Get columns.
 *
 * @return array
 */
protected function getColumns()
{
    return [
        Column::make('employee_no'),
        Column::make('name'),
        Column::make('address'),
        Column::make('birthplace'),
        Column::make('birthdate'),
        Column::make('age'),
        Column::make('occupation'),
        Column::make('status'),
        Column::make('gender'),
        Column::make('startdate'),
    ];
}

and here is my code in my controller for rendering the table

public function index(InfoDataTable $dataTable)
{
          $User = User::where('id', Auth::id())->first();
          if($User->role == 'superadmin'){
          return $dataTable->render('superadmin.index');
            } else {
              return $dataTable->render('admin.index');
            }
 }

and my blade looks like this

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
            <div class="card">
                <div class="card-header">Dashboard</div>
                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
                </div>
            <div class="card-body">
              <div class="table-responsive">
                <div class="panel panel-default">
                {{(!! $dataTable->table() !!)}}
              </div>
            </div>
            </div>
          </div>
        </div>
</div>
@stop
@push('scripts')
  {!! $dataTable->scripts() !!}
@endpush

my current view looks like this

any suggestions? sorry for my broken english, tried many tutorial but can't find the correct one

1

There are 1 answers

0
Ngô Minh On

Actions column is default for yajra datatables. So I found how to remove it: https://yajrabox.com/docs/laravel-datatables/6.0/remove-column (I have never tried this)

public function dataTable($query)
{
    return datatables()
        ->eloquent($query)
        ->removeColumn('action');
}

If you want to edit actions column, try my code:

public function dataTable($query)
{
    $dataTable = new EloquentDataTable($query);

    return $dataTable->addColumn('action', 'folderNameInViewfolder.datatables_actions');
}

This is what in datatables_actions (full name: datatables_actions.blade.php)

{!! Form::open(['route' => ['routename.destroy', $id], 'method' => 'delete']) !!}
<div class='btn-group'>
    <a href="{{ route('routename.show', $id) }}" class='btn btn-default btn-xs'>
        <i class="glyphicon glyphicon-eye-open"></i>
    </a>
    <a href="{{ route('routename.edit', $id) }}" class='btn btn-default btn-xs'>
        <i class="glyphicon glyphicon-edit"></i>
    </a>
    {!! Form::button('<i class="glyphicon glyphicon-trash"></i>', [
        'type' => 'submit',
        'class' => 'btn btn-danger btn-xs',
        'onclick' => "return confirm('Are you sure?')"
    ]) !!}
</div>
{!! Form::close() !!}

My code is different from yours, so I will show my code:

Datatables code:

public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'cachthuclamviecs.datatables_actions');
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\Cachthuclamviec $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(Cachthuclamviec $model)
    {
        return $model->newQuery();
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->addAction(['width' => '120px', 'printable' => false])
            ->parameters([
                'dom'       => 'Bfrtip',
                'stateSave' => true,
                'order'     => [[0, 'desc']],
                'buttons'   => [
                    ['extend' => 'create', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-plus"></i> Thêm</span>'],
                    ['extend' => 'export', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-download"></i> Xuất&nbsp;<span class="caret"></span></span>'],
                    ['extend' => 'print', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-print"></i> In</span>'],
                    ['extend' => 'reset', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-undo"></i> Cài lại</span>'],
                    ['extend' => 'reload', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-refresh"></i> Tải lại</span>'],
                ],
            ]);
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'cachthuclamviec'
        ];
    }

Controller code:

public function index(CachthuclamviecDataTable $cachthuclamviecDataTable)
{
    return $cachthuclamviecDataTable->render('cachthuclamviecs.index');
}

Blade code:

@section('css')
    @include('layouts.datatables_css')
@endsection

{!! $dataTable->table(['width' => '100%', 'class' => 'table table-striped table-bordered']) !!}

@push('scripts')
    @include('layouts.datatables_js')
    {!! $dataTable->scripts() !!}
@endpush

datatables_actions blade code:

{!! Form::open(['route' => ['cachthuclamviecs.destroy', $id], 'method' => 'delete']) !!}
<div class='btn-group'>
    <a href="{{ route('cachthuclamviecs.show', $id) }}" class='btn btn-default btn-xs'>
        <i class="glyphicon glyphicon-eye-open"></i>
    </a>
    <a href="{{ route('cachthuclamviecs.edit', $id) }}" class='btn btn-default btn-xs'>
        <i class="glyphicon glyphicon-edit"></i>
    </a>
    {!! Form::button('<i class="glyphicon glyphicon-trash"></i>', [
        'type' => 'submit',
        'class' => 'btn btn-danger btn-xs',
        'onclick' => "return confirm('Are you sure?')"
    ]) !!}
</div>
{!! Form::close() !!}

Put file datatables_actions here: datatables_actions:
datatables_actions

Code maybe have differences because of Boostrap, jQuery,... version