Datatables in Laravel - php

I'm new to Laravel and I'm trying to implement Datatables into my project but it doesn't seem to work.
My app.blade.php :
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/af-2.2.2/b-1.5.1/datatables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/af-2.2.2/b-1.5.1/datatables.min.css"/>
My view where my target table is:
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Liste des tickets Exporter</h3>
</div>
<div class="panel-body">
<table class="table table-striped table-bordered table-hovered" id="table">
<thead>
<tr>
<td>Objet</td>
<td>Urgence</td>
<td>Statut</td>
<td>Utilisateur</td>
<td>Actions</td>
</tr>
</thead>
#foreach ($tickets as $ticket)
<tbody>
<tr>
<td width="25%">{{ $ticket->message}}</td>
<td width="25%">{{ $ticket->urgence->niveau}}</td>
<td width="25%">{{ $ticket->statut}}</td>
<td width="25%">{{ $ticket->utilisateur->name}}</td>
<td style='white-space: nowrap'>
Voir
Supprimer
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $tickets->render()}}
</div>
</div>
<script>
$(document).ready( function () {
$('#table').DataTable();
} );
</script>
Can you help me do so?
Edit : This is my TicketsController Code as required:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Tickets;
use Auth;
use Session;
use App\Gestion;
use Excel;
use App\assistance;
use Carbon\Carbon;
class TicketsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('admin')->only('voir');
}/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$urgences=DB::table('urgences')->pluck('niveau','id');
$assistances=DB::table('assistances')->pluck('level','id');
return view('tickets.creation',compact('urgences','assistances'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data=$request->all();
$this->validate($request,[
'message'=>'required|min:8',
'urgence_id'=>'required',
'typeassistance'=>'required',
]);
$data=array_add($data,'utilisateur_id',Auth::user()->id);
Tickets::create($data);
Session::flash('message','Vous avez ouvert un nouveau ticket.');
return redirect('/home');
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function voir($id)
{
$gestions=Gestion::where('ticket_id',$id)->get();
$assistances=DB::table('assistances')->pluck('level','id');
$tickets=Tickets::findOrFail($id);
if($tickets->statut=='nouveau'){
$tickets->statut='ouvert';
$tickets->save();
}
return view('tickets.show',compact('tickets','gestions','assistances'));
}
public function exportxls(){
$weeklyTickets = \App\Tickets::whereBetween('created_at', array(date("Y-m-d", strtotime("-7 days")), date('Y-m-d')))->get();
Excel::create('tickets', function($excel) use ($weeklyTickets){
$excel->sheet('tickets', function($sheet) use ($weeklyTickets){
$sheet->loadView('export.ticketsexcel', array('weeklyTickets' => $weeklyTickets));
})->export('xls');
});
return redirect('/');
}
public function delete($id)
{
$tickets=Tickets::findOrFail($id);
$tickets->delete();
Session::flash('message','Vous avez bien supprimé le ticket.');
return redirect('/');
}
}
I would like my tables to be like the basic Datatables style, with the search bar. The search bar is a must for me, someone actually told me to use Datatables because i needed an instant search bar, I don't really mind the other parts of Datatables.
Thanks in advance.

Related

Difficult issue to troubleshoot with Gate and Livewire

I have been trying to solve this issue for days, but I struggle.
I tried to pack this post with as many information as I could because it is not easy to troubleshoot.
"laravel/framework": "9.41.0",
"spatie/laravel-permission": "5.7"
Explanation
If I drag any rows with the admin role, it works perfectly.
If I drag a role with the manager role, the first drag works, on the second drag I get this:
Unknown named parameter $id <---THIS IS THE ERROR
Routes:
require __DIR__ . '/auth.php';
Route::prefix('/')
->middleware(['auth','verified'])
->group(function () {
Route::resource('roles', RoleController::class);
Route::resource('permissions', PermissionController::class);
Route::resource('users', UserController::class);
Route::resource('popups', PopupController::class);
});
Illuminate\ Auth\ Access \ Gate : 535 callAuthCallback
/**
* Resolve and call the appropriate authorization callback.
*
* #param \Illuminate\Contracts\Auth\Authenticatable|null $user
* #param string $ability
* #param array $arguments
* #return bool
*/
protected function callAuthCallback($user, $ability, array $arguments)
{
$callback = $this->resolveAuthCallback($user, $ability, $arguments);
return $callback($user, ...$arguments); //This line shows in RED
}
I using this library to drag and drop a table row:
https://github.com/nextapps-be/livewire-sortablejs
This is my component:
<table class="w-full max-w-full mb-4 bg-transparent">
<thead class="text-gray-700">
<tr>
<th class="px-4 py-3 text-left"></th>
<th class="px-4 py-3 text-left"></th>
<th class="px-4 py-3 text-left"></th>
<th></th>
</tr>
</thead>
<tbody wire:sortable="reorder" wire:sortable.options="{ animation: 100 }" class="text-gray-600">
#forelse($popups as $popup)
<tr wire:sortable.item="{{ $popup['id'] }}" wire:sortable.triggers="reorder" class="hover:bg-gray-50 {{ $popup['order'] === 1 ? 'bg-yellow-50' : '' }}" wire:key="popup-{{ $popup['id'] }}">
<td class="px-4 py-3 text-left">
{{ $popup['id'] ?? '-' }}
</td>
<td class="px-4 py-3 text-left">
{{ $popup['title'] ?? '-' }}
</td>
<td class="px-4 py-3 text-left">
{{ $popup['reset_popup_days'] ?? '-' }}
</td>
<td>
<button wire:sortable.handle>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 15L12 18.75 15.75 15m-7.5-6L12 5.25 15.75 9"/>
</svg>
</button>
</td>
</tr>
#empty
<tr>
<td colspan="7">
#lang('crud.common.no_items_found')
</td>
</tr>
#endforelse
</tbody>
</table>
The livewire class:
<?php
namespace App\Http\Livewire\Table\Popup;
use App\Models\Popup;
use Livewire\Component;
class Index extends Component
{
public $popups;
public function mount()
{
$this->popups = Popup::orderBy('order')->get();
}
public function reorder($reorderedIds)
{
$orderedIds = collect($reorderedIds)->sortBy('order')->pluck('value');
$this->popups = $orderedIds->map(function ($id) {
return collect($this->popups)->where('id', (int)$id)->first();
})->values();
foreach ($this->popups as $index => $popup) {
$popup = Popup::find($popup['id']);
$popup->order = $index + 1;
$popup->save();
}
}
public function render()
{
return view('livewire.table.popup.index', ['popups' => $this->popups]);
}
}
I am using Gates and Policies for the Laravel controllers(not using it on livewire components directly yet as I am not sure if I should).
This is my controller so when the user lands on the CRUD, he can access all the different pages.
<?php
namespace App\Http\Controllers;
use App\Models\Popup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\PopupStoreRequest;
use App\Http\Requests\PopupUpdateRequest;
class PopupController extends Controller
{
/**
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$this->authorize('view-any', Popup::class);
$search = $request->get('search', '');
$popups = Popup::search($search)
->latest()
->paginate(5)
->withQueryString();
return view('app.popups.index', compact('popups', 'search'));
}
/**
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$this->authorize('create', Popup::class);
return view('app.popups.create');
}
/**
* #param \App\Http\Requests\PopupStoreRequest $request
* #return \Illuminate\Http\Response
*/
public function store(PopupStoreRequest $request)
{
$this->authorize('create', Popup::class);
$validated = $request->validated();
if ($request->hasFile('image')) {
$validated['image'] = $request->file('image')->store('public');
}
//$latestOrder = Popup::orderBy('order')->get()->last();
$latestOrder = Popup::orderBy('order', 'desc')->first();
$order = $latestOrder ? $latestOrder->order + 1 : 0;
$popup = Popup::create(array_merge($validated, ['order' => $order]));
//$popup = Popup::create($validated);
return redirect()
->route('popups.edit', $popup)
->withSuccess(__('crud.common.created'));
}
/**
* #param \Illuminate\Http\Request $request
* #param \App\Models\Popup $popup
* #return \Illuminate\Http\Response
*/
public function show(Request $request, Popup $popup)
{
$this->authorize('view', $popup);
return view('app.popups.show', compact('popup'));
}
/**
* #param \Illuminate\Http\Request $request
* #param \App\Models\Popup $popup
* #return \Illuminate\Http\Response
*/
public function edit(Request $request, Popup $popup)
{
$this->authorize('update', $popup);
return view('app.popups.edit', compact('popup'));
}
/**
* #param \App\Http\Requests\PopupUpdateRequest $request
* #param \App\Models\Popup $popup
* #return \Illuminate\Http\Response
*/
public function update(PopupUpdateRequest $request, Popup $popup)
{
$this->authorize('update', $popup);
$validated = $request->validated();
if ($request->hasFile('image')) {
if ($popup->image) {
Storage::delete($popup->image);
}
$validated['image'] = $request->file('image')->store('public');
}
$popup->update($validated);
return redirect()
->route('popups.edit', $popup)
->withSuccess(__('crud.common.saved'));
}
/**
* #param \Illuminate\Http\Request $request
* #param \App\Models\Popup $popup
* #return \Illuminate\Http\Response
*/
public function destroy(Request $request, Popup $popup)
{
$this->authorize('delete', $popup);
if ($popup->image) {
Storage::delete($popup->image);
}
$popup->delete();
return redirect()
->route('popups.index')
->withSuccess(__('crud.common.removed'));
}
}
My policies:
<?php
namespace App\Policies;
use App\Models\User;
use App\Models\Popup;
use Illuminate\Auth\Access\HandlesAuthorization;
class PopupPolicy
{
use HandlesAuthorization;
/**
* Determine whether the popup can view any models.
*
* #param App\Models\User $user
* #return mixed
*/
public function viewAny(User $user)
{
return $user->hasPermissionTo('list popups');
}
/**
* Determine whether the popup can view the model.
*
* #param App\Models\User $user
* #param App\Models\Popup $model
* #return mixed
*/
public function view(User $user, Popup $model)
{
return $user->hasPermissionTo('view popups');
}
/**
* Determine whether the popup can create models.
*
* #param App\Models\User $user
* #return mixed
*/
public function create(User $user)
{
return $user->hasPermissionTo('create popups');
}
/**
* Determine whether the popup can update the model.
*
* #param App\Models\User $user
* #param App\Models\Popup $model
* #return mixed
*/
public function update(User $user, Popup $model)
{
return $user->hasPermissionTo('update popups');
}
/**
* Determine whether the popup can delete the model.
*
* #param App\Models\User $user
* #param App\Models\Popup $model
* #return mixed
*/
public function delete(User $user, Popup $model)
{
return $user->hasPermissionTo('delete popups');
}
/**
* Determine whether the user can delete multiple instances of the model.
*
* #param App\Models\User $user
* #param App\Models\Popup $model
* #return mixed
*/
public function deleteAny(User $user)
{
return $user->hasPermissionTo('delete popups');
}
/**
* Determine whether the popup can restore the model.
*
* #param App\Models\User $user
* #param App\Models\Popup $model
* #return mixed
*/
public function restore(User $user, Popup $model)
{
return false;
}
/**
* Determine whether the popup can permanently delete the model.
*
* #param App\Models\User $user
* #param App\Models\Popup $model
* #return mixed
*/
public function forceDelete(User $user, Popup $model)
{
return false;
}
}
And the manager is assigned:
Permission::create(['name' => 'list popups']);
Permission::create(['name' => 'view popups']);
Permission::create(['name' => 'create popups']);
Permission::create(['name' => 'update popups']);
Permission::create(['name' => 'delete popups']);
While the admin is assigned all the permissions like this:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
// Automatically finding the Policies
Gate::guessPolicyNamesUsing(function ($modelClass) {
return 'App\\Policies\\' . class_basename($modelClass) . 'Policy';
});
$this->registerPolicies();
// Implicitly grant "Super Admin" role all permission checks using can()
Gate::before(function ($user, $ability) {
logger($ability);
if ($user->isSuperAdmin()) {
return true;
}
});
}
}
[TRIED]
<?php
namespace App\Http\Livewire\Table\Popup;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Models\Popup;
use Livewire\Component;
class Index extends Component
{
use AuthorizesRequests;
public $popups;
public function mount()
{
//$this->popups = Popup::orderBy('order')->get()->toArray();
$this->popups = Popup::orderBy('order')->get();
}
public function reorder($reorderedIds)
{
$this->authorize('update', array($this->popups));
$orderedIds = collect($reorderedIds)->sortBy('order')->pluck('value');
$this->popups = $orderedIds->map(function ($id) {
return collect($this->popups)->where('id', (int)$id)->first();
})->values();
//logger($this->popups);
foreach ($this->popups as $index => $popup) {
$popup = Popup::find($popup['id']);
$popup->order = $index + 1;
$popup->save();
}
}
public function render()
{
return view('livewire.table.popup.index', ['popups' => $this->popups]);
}
}
But getting this:
403 THIS ACTION IS UNAUTHORIZED.
//Event with the action is authorised(I checked the database and it is 100% authorised.
I think array($this->popups) is causing the issue as the data is different from the controler update authorised method....But how can I solve this if both methods deal differently with the data. In the old controller the update was dealing with a $POST array, while $this->popups deals with a collection.
I think this issue is connected to this PHP 8 modification that makes string keys interpreted as function parameter names. So when the custom policy function is called with the argument unpacking (...) operator here:
return $callback($user, ...$arguments);
the $popup variable (which is behaving like an associative array) from e.g. $this->authorize('update', $popup); becomes the named arguments of the policy functions after the unpacking. However since the policy functions do not have an $id argument, they throw the error.
You can try to run the code with PHP 7 to confirm the source of the issue.
To fix this you can try to embed the extra arguments of authorize() in an array, so the first array unpacking will only deconstruct the outer array, so the $popup array remains intact:
$this->authorize('update', array($popup));
Or you can also remove the extra arguments of authorize() since you don't use them in the policy functions.

Laravel displays blank page after renaming a page

I renamed my index.blade.php file in my 'cluster' folder into overview.blade.php and all of a sudden cluster/overview displays a blank page. I renamed all my other methods pointing towards the page so I am not sure what is going wrong here. I think it has to do with renaming the index
EDIT: added the relevant code
VIEW
#extends('layouts.app')
#include('modal')
#section('content')
<body>
<div class="container">
<div class="row">
<div class="col-12">
<button class="button -dark center">
‹ Home
</button>
<a href="/cluster/create">
<button type="submit" class="button -green center float-right">Voeg cluster toe</button>
</a>
</div>
</div>
<table class="table">
<thead>
<tr>
<th scope="col"><strong>Cluster naam</strong></th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
<tbody>
#foreach($departments as $department)
<tr>
<form action="{{route('deletecluster', $department->id)}}" method="post" id="submit-button">
<td>{{$department->name}}</td>
#csrf
<td><button type="button" class="btn btn-info" data-toggle="modal" data-target="#registration">Bewerken</button></td>
<td><button class="btn btn-danger" type="submit">Verwijderen</button></td>
</form>
</tr>
#endforeach
</tbody>
</table >
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-button').on('submit', function(e){
$('#registration').modal('show');
e.preventDefault();
});
});
</script>
</body>
#endsection
ROUTING
Route::get('/', function () {
return view('auth/login');
});
Route::resource('event', 'EventController');
Route::resource('cluster', 'ClusterController');
Route::get('calendar', 'EventController#calendar');
Route::get('export', 'EventController#export');
Route::get('user/create', 'UserController#create');
Route::get('user/edit/{id}', 'UserController#edit');
Route::get('cluster/edit/{id}', 'ClusterController#edit');
Route::get('user/settings', 'UserController#settings')->name('settings');
Route::post('user/store', 'UserController#store');
Route::post('user/employeeStore', 'UserController#employeeStore');
Route::post('user/store_settings', 'UserController#settingsStore');
Route::post('user/addShift', 'UserController#addShift');
Route::post('user/togglemail', 'UserController#toggleMail');
Route::get('user/overview', 'UserController#overview');
Route::get('cluster/overview', 'ClusterController#overview')->name('overview');
Route::post('user/delete{id}', 'UserController#deleteUser')->name('deleteuser');
Route::post('cluster/delete{id}','ClusterController#deleteCluster')->name('deletecluster');
Route::post('event/store', 'EventController#store');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
//Route::get('laravel-send-email', 'EmailController#sendMail');
Route::get('user/changepassword', 'UserController#changePassword');
Route::post('user/updatepassword', 'UserController#updatePassword')->name('updatepassword');
CONTROLLER
class ClusterController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function overview()
{
$departments = Department::all();
return view ('cluster.overview')->with('departments', $departments);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$shift_types = shift_type::all();
return view('cluster.create')->with('shift_types', $shift_types);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$department = new Department();
$department->name = $request->input('clustername');
$department->save();
$typeArray = explode(',', $request->input('types'));
foreach($typeArray as $type) {
$shift_type = new ShiftType();
$shift_type ->shift_name = $type;
$shift_type->save();
$department_shift_type = new DepartmentShiftType();
$department_shift_type->department_id = $department->id;
$department_shift_type->shift_type_id = $shift_type->id;
$department_shift_type->save();
}
return $department->id;
}
/**
* 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)
{
$departmentshift = DepartmentShiftType::findOrFail($id);
$departmentshifts = DepartmentShiftType::all();
$shifts = ShiftType::all();
$shift = ShiftType::findOrFail($id);
$shift_id = $departmentshift->shift_type_id;
$department = Department::findOrFail($id);
return view('cluster.edit')->with('department', $department)->with('departmentshift', $departmentshift)->with('shift_id', $shift_id)->with('departmentshifts', $departmentshifts)->with('shifts', $shifts)->with('shift', $shift );
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function deleteCluster($id)
{
$department = Department::findOrFail($id);
$department->delete();
return redirect('cluster.overview');
}
public function destroy($id)
{
//
}
}
Move this line:
Route::get('cluster/overview', 'ClusterController#overview')->name('overview');
above this one:
Route::resource('cluster', 'ClusterController');
Laravel thinks you are trying to call this route:
/cluster/{cluster}
public function show($id)
{
//
}
You can confirm this by adding some return value in the show method
public function show($id)
{
dd('foobar');
}

Problem displaying the data from my 'artists' table with Laravel

I do not manage to display the data from my database (I'm working with Laragon).
I already tried to change some names (variables etc.) here and there but I can't find where come from the problem.
I was able to display nothing first so I needed to change:
resources\views\artist\index.php -> resources\views\artists\index.blade.php
I probalby need to change more things in the code but I don't know where.
VIEW (views\artists\index.blade.php)
#extends('layouts.app')
#section('title', 'Liste des artistes')
#section('content')
<h1>Liste des {{ $resource }}</h1>
<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
#foreach($artists as $artist)
<tr>
<td>{{ $artist->firstname }}</td>
<td>{{ $artist->lastname }}</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
ROUTES (routes\web.php)
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('artists', 'ArtistController#index');
CONTROLLER (Controllers\ArtistController.php)
<?php
namespace App\Http\Controllers;
use App\Artist;
use Illuminate\Http\Request;
class ArtistController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
/*
Take the artist from the db
and send it to a specific template
*/
$artists = Artist::all();
return view('artists.index',
[
'artists' => $artists,
'resource' => 'artistes',
]);
}
/**
* 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 \App\Artist $artist
* #return \Illuminate\Http\Response
*/
public function show(Artist $artist)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Artist $artist
* #return \Illuminate\Http\Response
*/
public function edit(Artist $artist)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Artist $artist
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Artist $artist)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Artist $artist
* #return \Illuminate\Http\Response
*/
public function destroy(Artist $artist)
{
//
}
}
DATABASE (database\ArtistsTableSeeder.php)
<?php
use Illuminate\Database\Seeder;
class ArtistsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$artists = [
['firstname'=>'Bob','lastname'=>'Sull'],
['firstname'=>'Marc','lastname'=>'Flynn'],
['firstname'=>'Fred','lastname'=>'Durand'],
];
foreach ($artists as $a) {
DB::table('artists')->insert([
'firstname' => $a['firstname'],
'lastname' => $a['lastname'],
]);
}
}
}
The only thing who get displayed on my browser when I go to 127.0.0.1:8000/artists is:
**Liste des Artistes**
Firstname Lastname
But nothing from the content of my Artistes table is displayed.
Thank you very much guys, the problems was that I needed to change the names of my columns...
FirstName LastName to Firstname Lastname
The data get displayed properly now.

Undefined variable of view in laravel 5.4

I define a variable in view. But problem is that it shows undefined. My task is, first i take all the input from user using form helper then i want to post it to the store function & do some calculation and then pass it to the view for showing purpose. But i tried it, unfortunately shows undefined.Undefined variable is "totalamount" Here i attached all the code:
controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\TestSetup;
use Illuminate\Support\Facades\Input;
class TestRequestController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$allTestNames=TestSetup::all()->pluck('test_name','id');
// $testNames=TestSetup::orderBy('test_name')
// ->get();
return view('testrequestentries.createTestRequestEntry')->withAlltestnames($allTestNames);
// return view('testrequestentries.createTestRequestEntry');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// if(Input::get('Add')) {
$total=$request->fee+$total;
return view('testrequestentries.createTestRequestEntry')->withTotalamount($total);
// }else if(Input::get('Save')){
//
// }
}
/**
* 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)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
view
#extends ('main')
#section('title','|Test Request Entry')
#section('stylesheets')
{!! Html:: style('css/parsley.css')!!}
#endsection
#section('content')
{!! Form::open(['route' => 'testrequests.store','data-parsley-validate'=>'']) !!}
{{Form::label('patient_name','Name of the Patient:')}}
{{Form::text('patient_name',null,array('class' => 'form-control','required'=>'', 'data-parsley-required-message' => 'Patient Name is required'))}}
{{Form::label('date_of_birth','Date Of Birth:')}}
{{Form::date('date_of_birth',null,array('class' => 'form-control','data-parsley-required' =>'true')) }}
{{Form::label('mobile_no','Mobile No:')}}
{{Form::text('mobile_no',null,array('class' => 'form-control','type'=> 'number','maxlength'=>'11','minlength' => '11','required'=>'', 'data-parsley-required-message' => 'Mobile No is required'))}}
{{Form::label('test_id','Select Test:')}}
{{Form::select('test_id',$alltestnames,null,['class'=>'form-control','required'=>'','placeholder' => 'Pick a Test...'])}}
{{Form::label('fee','Fee:')}}
{{Form::text('fee',null,array('class' => 'form-control','required'=>'', 'data-parsley-required-message' => 'Fee is required'))}}
{{Form::submit('Add',array('class' => 'btn btn-lg btn-block btn-success','style' => 'margin-top:10px;'))}}
<table class="table table-bordered" style="margin-top: 50px;">
<thead>
<tr>
<th>SL</th>
<th>Test Name</th>
<th>Fee</th>
<th>Type Name</th>
</tr>
</thead>
#php ($i=1)
<tbody>
<tr>
<th scope="row">{{$i}}</th>
<td>{{$totalamount}}</td>
</tr>
</tbody>
#php ($i++)
</table>
{!! Form::close() !!}
#section('scripts')
{!! Html:: script('js/parsley.min.js') !!}
#endsection
#endsection
I bet the view is returned from create() here, so change this:
return view('testrequestentries.createTestRequestEntry')->withAlltestnames($allTestNames);
To:
return view('testrequestentries.createTestRequestEntry', [
'alltestnames' => $allTestNames,
'totalamount' => $total
]);
In the store() method, do not return the view. Redirect back() or to index() or show() methods instead.
first thing first: check the value of $total=$request->fee+$total;
ie: put "dd('$total', $total);" right after the line you set it, before the return.
second: make it simplier return view(...)->with('totalAmount', $total);
test the value of $totalAmount in the view (BLADE file)
ie: {{dump('totalAmount', $totalAmount)}}
Anyway the store() method does NOT store anything ... WHY THAT?

Trying to get property of non-object laravel 5.3, index.blade

I am stuck with this error in Laravel:
Trying to get property of non-object (View: C:...\resources\views\admin\users\index.blade.php)
Is anything wrong with my code?
This My index
#extends('layouts.admin')
#section('content')
<h1>Users</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Created</th>
<th>Updated</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
#if($users)
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->role->name}}</td>
<td>{{$user->active == 1 ? 'Active' : 'Not Active'}}</td>
<td>{{$user->created_at->diffForHumans()}}</td>
<td>{{$user->updated_at->diffForHumans()}}</td>
<td>{{$user->photo_id}}</td>
</tr>
#endforeach
#endif
</tbody>
</table>
#stop
This my Controller
public function index()
{
//
$users = User::all();
return view('admin.users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
$roles = Role::pluck('name','id')->all();
return view('admin.users.create', compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(UsersRequest $request)
{
//Buat bikin create dengan method ini
User::create($request->all());
return redirect('/admin/users');
// return $request->all();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
return view('admin.users.show');
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
return view('admin.users.edit');
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
This my Request
class UsersRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'name'=>'required',
'password'=>'required',
'email'=>'required',
'active'=>'required',
'role_id'=>'required',
'photo_id'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:7098',
];
}
}
This means (inside the controller)
$users = User::all();
returns empty object. There are no users in the db. The error probably comes from (admin/users/index.blade.php)
{{$user->id}}
and the other lines follow as well.
Before looping over the users, check if the data is empty. Correct this line
#if($users)
to look like this
#if($users->toArray())
It will return an empty array if there are no records for users and never enter in loop.
This will correct your error.
PS: Put an else statement for the #if statement with proper message so you can know it worked.
Please change this line
<td>{{$user->role->name}}</td>
to
<td>{{ $user->role ? $user->role->name : '-' }}</td>
Should work now... :)

Categories