Laravel displays blank page after renaming a page - php

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');
}

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.

How to Insert data through multiple forms to multiple tables in laravel

Hi i am new to laravel i have 3 forms ie customer ,service,contact all have different tables like customer ,service,contact i need to do insert for these in database in laravel.
Service Form:
<form method="POST" action="{{ route('service.store') }}">
#csrf
<div class="input-w">
<label class="label-style">Service Type:</label>
<span><select class="form-control" required >
<option type="brillare">Brillare</option>
<option type="hair">Hair</option>
</select></span>
</div>
<div class="input-w">
<label name="service_name">Service Name:</label>
<span><input id="service_name" name="service_name" class="form-control" placeholder="Service Name" required ></span>
</div>
<div class="input-w">
<label name="service_price">Service Price:</label>
<span><input type="number" id="service_price" name="service_price" class="form-control" required placeholder="0000.00"></span>
</div>
<div align="center" class="button_style">
<p style="margin:15px -40px 20px 182px"><input type="submit" name="submit" id="submit_service" value="Submit" class="btn btn-outline-success"></p>
</div>
</form>
Migration:
Route::get('/service', function () {
return view('service');
});
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ServiceTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('service', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('servicetype');
$table->string('servicename');
$table->string('serviceprice');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('service');
}
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ServiceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view("service");
}
/**
* 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, Service $service)
{
//
$service->servicetype = $request->service_type;
$service->servicename = $request->service_name;
$service->serviceprice = $request->service_price;
$service->create();
return redirect()->route('service.show');
}
/**
* 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)
{
//
}
}
i need
service form insert to service table
customer form insert to customer table
contact form insert to contact table
in laravel 5.8
In this case you have 3 entities.
Customer
Service
Contact
For all 3 entities you would want to have a model, a controller and a migration. If the entities have relations between one and other you can specify those in the model. Take a look at the link for more information about relationships in laravel.
https://laravel.com/docs/master/eloquent-relationships
When you have made the relations in the model, made the migrations its time to move on to the controller.
In the controller you will have the following functions:
public function index(Contact $model)
{
// return index view
}
public function create()
{
// return create form view
}
// Option 1
public function store(Request $request, Service $service)
{
$service->create($request->all);
return redirect()->route('your.route');
}
// Option 2
public function store(Request $request, Service $service)
{
$service->servicetype = $request->service_type;
$service->servicename = $request->service_name;
$service->serviceprice = $request->service_price;
$service->create();
return redirect()->route('your.route');
}
public function edit()
{
// return edit view
}
public function update(Request $request, Service $service)
{
$service->update($request->all);
//return view
}
public function destory(Service $service)
{
$service->delete();
// return view
}

Why $post is not an object in the third code?

I started learning Laravel today and I've ran into a problem.
There are 3 seperated posts. Each one has titles and I made an other title too which should be in the url of the page of the posts, for example:
something.com/posts/post_three instead of posts/3
With the id version (posts/3) it worked perfectly, but I tried to change the code so it will go to posts/post_three, but I keep getting the following error:
Trying to get property 'created_at' of non-object (View:
C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php)
I have the following codes which I've changed something in:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('urltitle', 'desc')->paginate(5);
return view('posts.index')->with('posts', $posts);
}
/**
* 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($urltitle)
{
$post = Post::find($urltitle);
return view('posts.show')->with('post', $post);
}
/**
* 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)
{
//
}
}
-
#extends('pages.layouts.app')
#section('content')
<h1 style="text-align: center">Posts</h1>
#if(count($posts) > 0)
#foreach($posts as $post)
{{$post->urltitle}}
<div class="card" style="padding-top: 8px">
<div class="card-body">
<h3>{{$post->title}}</h3>
<small>Written on: {{$post->created_at}}</small>
</div>
</div>
#endforeach
<div style="justify-content: center; display: flex;">{{$posts->links()}}</div>
#else
<p>No posts found</p>
#endif
#endsection
-
And here is the code which can't "recognise" $post
#extends('pages.layouts.app')
#section('content')
<div class="jumbotron text-center">
Go Back
<h1>{{$post->title}}</h1>
<div>{{$post->body}}</div>
<hr>
<small>Written at {{$post->created_at}}</small>
</div>
#endsection
This is where the error occurs:
public function show($urltitle)
{
$post = Post::find($urltitle); // <----
return view('posts.show')->with('post', $post);
}
The find() method will check for a primmary key (id by default) that hold the given value, so this both sentences are equal:
$post = Post::find($id);
// equals to:
$post = Post::where('id', $id)->first();
but given the fact that you are passing the urltitle instead of the $id, you should use a more generic approach:
$post = Post::where('urltitle', $urltitle)->first();
Also, as #devon said, you should check if a value is returned:
$post = Post::where('urltitle', $urltitle)->first();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if( ! $post)
{
// do something
}
or throw an error if the query returns nothing:
$post = Post::where('urltitle', $urltitle)->firstOrFail();
^^^^^^^^^^^^^

laravel 5.6 not reading variable from controller in laravel

I am new to laravel so pardon me if this question seems stupid. I am trying to do a basic CRUD app, the create and read seems to work fine but am having issues with editing, updating and deleting. When I click the edit button it returns undefined variable log_books but to my understanding I think I have declared it. Please help.
controller name: logbook.php
namespace App\Http\Controllers;
use Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\log_book;
use DB;
use Illuminate\Support\Facades\Auth;
class logbook extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
/**
*
*#if(Auth::check())
*/
$log_books = log_book::all();
return view('home')->with('log_books',$log_books);
/**
*
*#endif
*/
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
/**
*
* #if(Auth::check())
*/
return view('log_books.create');
/**
*
* #endif
*/
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
log_book::create(Request::all());
return redirect('home')->with('message','name has been added successfully');
}
/**
* 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)
{
//
/**
*
*#if(Auth::check())
*/
$log_books = log_book::findorFail($id);
//$logs = DB::table('log_books')->where('id', $id)->first();
return view('log_books.edit', compact($log_books))->with('id', $id);
/**
*
*#endif
*/
}
/**
* 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)
{
//
$log_books = log_books::findorFail($id);
$destroy = $log_books->delete();
if($destroy) {
return redirect('home', compact($log_books))->with('message', 'Record has been deleted');
}
}
}
My Route: web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('create', function () {
return view('create');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/create', 'logbook#create')->name('create');
Route::post('store', 'logbook#store');
Route::get('/home', 'logbook#index');
Route::get('edit/{id}', 'logbook#edit');
Route::delete('destroy/{id}', 'logbook#destroy');
My View: home.blade.php
#foreach($log_books as $row)
<tr>
<td>{{$row->name}}</td>
<td>{{$row->present_date}}</td>
<td>{{$row->time_in}}</td>
<td>{{$row->time_out}}</td>
<td><input type="button" class="btn btn-success" value="Edit"> <input type="button" class="btn btn-danger" value="Delete"></td>
</tr>
#endforeach
edit view: edit.blade.php
<form method="post" action="edit">
{{csrf_field()}}
<input type="hidden" name="_method" value="PUT">
<input required="yes" type="text" placeholder="Full name" class="form-control" name="name" value="{{$log_books->name}}"><br>
<input required="yes" onfocus="this.type= 'date'" onblur="this.type='text'" placeholder="Date" class="form-control" name="present_date" value="{{$log_books->present_date}}"><br>
<input required="yes" onfocus="this.type= 'time'" onblur="this.type='text'" placeholder="Time in" class="form-control" name="time_in" value="{{$log_books->time_in}}"><br>
<input onfocus="this.type= 'time'" onblur="this.type='text'" placeholder="Time out" class="form-control" name="time_out" value="{{$log_books->time_out}}"><br>
<input type="submit" class="btn btn-primary" value="Submit" name="submit">
</form>
Pardon my code if it looks messed up, the create and edit view are both in a folder called log_books. Thanks for your help.
Your edit method is passing an invalid value to compact:
return view('log_books.edit', compact($log_books))->with('id', $id);
Should most likely be the 'name' of the variable you want to compact, not the variable itself:
return view('log_books.edit', compact('log_books'))->with('id', $id);
To avoid these types of mistakes completely, just define the array:
return view('log_books.edit', ['log_books' => $log_books])...
Laravel has Route model binding, you may use this feature in show and edit methods as follows:
In Controller
public function edit(Log_Book $log_book)
{
return view('log_books.edit', compact($log_book));
}
In web.php
Route::get('/edit/{log_book}', 'logbook#edit');
Also you don't need to check auth in controller methods, use auth middleware.
In Controller
public function __construct()
{
return $this->middleware('auth');
}

Datatables in Laravel

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.

Categories