Ad

Laravel, Yajrabox Datatables - Table Not Displaying Rows

- 1 answer

My page loads correctly and but the data rows do not show. I've been using a video tutorial and copying it best I can for my own project. I have put my code below and I would really appreciate any help. I'm really struggling to understand hjow datatable integrate with laravel.

app\http\controller\DatatablesController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Activity;

class DatatablesController extends Controller
{

    public function getIndex()
    {
        return view('activities\index');
    }


    public function getData() {

        $query=Activity::all();

    return Datatables::of($query)->addColumn('id', function ($query) {
            return $query->id;
        })->addColumn('when', function ($query) {
            return $query->created_date;
        })->addColumn('activity', function ($query) {
            return $query->activity;
        })->addColumn('learned', function ($query) {
            return $query->learned;
        })->addColumn('role', function ($query) {
            return $query->role;
        })->addColumn('hours', function ($query) {
            return $query->hours;
        })->addColumn('name', function ($query) {
            return $query->user_id;
        })->make(true);
    }
}

app\http\controller\ActivitiesController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Activity;
use DB;
use Yajra\Datatables\Datatables;
use Redirect,Response;




class ActivitiesController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //$activities = Activity::all()->take(1);   // just one 
        //$activities = Activity::all(); //all
        //$activity = Activity::where('hours', '>', '5.0')->get(); // Where clause
        //$activities = Activity::orderBy('when', 'asc')->get();  // Order by - show all
        //$activities = DB::select('SELECT * FROM activities');   // SQL statement 
        //$activities = Activity::orderBy('when', 'asc')->get();  // Order by - show all

        return view('activities\index');//->with('activities', $activities);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('activities\create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'when' => 'required|date',
            'activity' => 'required', 
            'learned' => 'required',
            'role' => 'required',
            'hours' => 'required|numeric',
        ]);

        // create Activity
        $activity = new Activity;
        $activity->when = $request->input('when'); // these are the names from the form
        $activity->activity = $request->input('activity');
        $activity->learned = $request->input('learned');
        $activity->role = $request->input('role');
        $activity->hours = $request->input('hours');
        $activity->user_id = auth()->user()->id;
        $activity->save();

        return redirect('/activities')->with('success', 'Activity created');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $activity = Activity::find($id);
        return view('activities\show')->with('activity', $activity);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $activity = Activity::find($id);
        return view('activities\edit')->with('activity', $activity);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'when' => 'required|date',
            'activity' => 'required', 
            'learned' => 'required',
            'role' => 'required',
            'hours' => 'required|numeric',
        ]);

        // create Activity
        $activity = Activity::find($id);
        $activity->when = $request->input('when'); // these are the names from the form
        $activity->activity = $request->input('activity');
        $activity->learned = $request->input('learned');
        $activity->role = $request->input('role');
        $activity->hours = $request->input('hours');
        $activity->save();

        return redirect('/activities')->with('success', 'Activity updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $activity = Activity::find($id);
        $activity->delete();
        return redirect('/activities')->with('success', 'Activity Removed');
    } 


}

App\Activity.php

<?php

namespace App;

use App\User;
use Illuminate\Database\Eloquent\Model;

class Activity extends Model
{
    // Table name
    public $table = 'activities';
    // Primary key
    public $promaryKey = 'id';
    // Timestamps (true by default)
    public $timestamps = true;

    public function user()
    {
        return $this->belongsTo('App\User');
    }


}

\web.php

<?php

Route::get('/', '[email protected]');
Route::get('/testing', '[email protected]');

Route::resource('activities', 'ActivitiesController');

Auth::routes();

Route::get('/dashboard', '[email protected]');

//datatable
Route::get('getactivities', '[email protected]')->name('get.activities');

App\resources\activities\index.blade.php


@extends('layouts/app')

@section('css')
    <style>
        .grid33 {

            width: 100vw;
            display: grid;
            width: 100%;
            grid-template-columns: 1fr minmax(750px, 6fr) 1fr;
            grid-template-rows: 40px 6fr 1fr;
            grid-template-areas:
                "left head right"
                "left main right"
                "left foot right"; 
        }

        .datatable {
            grid-area: main;
            }
        .datafooter {
            grid-area: foot;
        }

        .datahead {
            grid-area: head;
        }
    </style>
@endsection

@section('content')


    <div class="grid33">
        <div class="datahead">
                <h3>Activities</h3>
                @include('inc\messages')
        </div>
        <div class="datatable">
                <table class="table" id="actvities-table">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Month/Year</th>
                            <th scope="col">Course / Guided Learning / Training Activity</th>
                            <th scope="col">What New/Increased Skills/Knowledge Learned?</th>
                            <th scope="col">How Does This Apply To Your Role/Responsibilities?</th>
                            <th scope="col">Training Hours</th>
                            <th scope="col">User</th>
                        </tr>
                    </thead>
                </table>


                <br>
                <a target="_blank" rel="nofollow noreferrer" href="/activities/create" class="btn btn-outline-primary btn-sm float-right">Add an activity</a>
        </div>

        <div class="datafooter">

        </div>
    </div>

@endsection

@section('scripts')

    <script>
 $(function() {
            $('#actvities-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{!! route('get.activities') !!}',
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'when', name: 'when' },
                    { data: 'activity', name: 'activity' },
                    { data: 'learned', name: 'learned' },
                    { data: 'role', name: 'role' }
                    { data: 'hours', name: 'hours' }
                    { data: 'user', name: 'user' }
                ]
            });
        });
    </script>
@endsection

App\resources\layouts\app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>


    @yield('scripts')


    <!-- Fonts -->
    <link rel="dns-prefetch" target="_blank" rel="nofollow noreferrer" href="//fonts.gstatic.com">
    <link target="_blank" rel="nofollow noreferrer" href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link target="_blank" rel="nofollow noreferrer" href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link rel="stylesheet" target="_blank" rel="nofollow noreferrer" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">


    @yield('css')

</head>
<body>
    <div id="app">
        @include('inc\navbar')
        <main class="py-4">

                @yield('content')            
        </main>
    </div>
</body>
</html>
Ad

Answer

In Your DatatablesController

 <?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 use Yajra\Datatables\Datatables;
 use App\Activity;

 class DatatablesController extends Controller
 {

   public function getIndex()
   {
    return view('activities.index');
   }


    public function getData() {
       $query=Activity::all();

    return Datatables::of($query)->addColumn('id', function ($query) {
        return $query->id;
    })->addColumn('when', function ($query) {

        return $query->created_date;
    })->addColumn('activity', function ($query) {
        return $query->activity;
    })->addColumn('learned', function ($query) {
        return $query->learned;
    })->addColumn('role', function ($query) {

         return $query->role;
    })->addColumn('hours', function ($query) {

        return $query->hours;
    })->addColumn('name', function ($query) {
        return $query->user_id;
    })->make(true);

   }
 }

and in your blade file

       @extends('layouts/app')

     @section('scripts')

    <script>
$(document).ready( function () {
    $('#myTable').DataTable();
} );
    </script>

   @endsection

    @section('css')
<style>
    .grid33 {

        width: 100vw;
        display: grid;
        width: 100%;
        grid-template-columns: 1fr minmax(750px, 6fr) 1fr;
        grid-template-rows: 40px 6fr 1fr;
        grid-template-areas:
            "left head right"
            "left main right"
            "left foot right"; 
    }

    .datatable {
        grid-area: main;
        }
    .datafooter {
        grid-area: foot;
    }

    .datahead {
        grid-area: head;
    }
  </style>
       @endsection

    @section('content')


  <div class="grid33">
    <div class="datahead">
            <h3>Activities</h3>
            @include('inc\messages')
    </div>
    <div class="datatable">
            <table class="table" id="actvities-table">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Month/Year</th>
                        <th scope="col">Course / Guided Learning / Training 
                 Activity</th>
                        <th scope="col">What New/Increased Skills/Knowledge 
                  Learned?</th>
                        <th scope="col">How Does This Apply To Your 
              Role/Responsibilities?</th>
                        <th scope="col">Training Hours</th>
                        <th scope="col">User</th>
                    </tr>
                </thead>
            </table>


            <br>
            <a target="_blank" rel="nofollow noreferrer" href="/activities/create" class="btn btn-outline-primary btn-sm 
     float-right">Add an activity</a>
    </div>

    <div class="datafooter">

    </div>
</div>

 @endsection

  @section('scripts')
    <script>
        $(function() {
            $('#actvities-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{!! route('get.activities') !!}',
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'when', name: 'when' },
                    { data: 'activity', name: 'activity' },
                    { data: 'learned', name: 'learned' },
                    { data: 'role', name: 'role' }
                    { data: 'hours', name: 'hours' }
                    { data: 'user', name: 'user' }
                ]
            });
        });
   </script>

i hope it will work

Ad
source: stackoverflow.com
Ad