How can I get my custom gate working in Laravel? - php

I am trying to create a custom gate that allows users of the "Administrator" team to access the Users index page. However, it functions exactly the opposite of what I want to achieve and I do not seem to understand where am I wrong here.
It always returns "false" regardless of the user belongs to an Admin team or not.
Help is appreciated. Thank you.
User.php :
public function AdminTeam(string $team)
{
return null !== $this->teams()->where('name', $team)->first();
}
AuthServiceProvider.php :
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('is-admin', function ($user){
return $user->AdminTeam('Administrator');
});
}
UserController.php :
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (Gate::allows('is-admin')) {
return view('admin.users.index', ['users' => User::paginate(10)]);
}
dd('you need to be admin!');
}
index.blade.php :
#can('is-admin')
#foreach($users as $user)
<tr>
<th scope="row">{{ $user->user_id }}</th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->created_at }}</td>
<td>{{ $user->updated_at }}</td>
<td>
<a class="btn btn-sm btn-primary" href="{{ route('admin.users.edit', $user->user_id) }}"
role="button">Bearbeiten</a>
<button type="button" class="btn btn-sm btn-danger"
onclick="event.preventDefault();
document.getElementById('delete-user-form-{{ $user->user_id }}').submit()">
Löschen
</button>
<form id="delete-user-form-{{ $user->user_id }}"
action="{{ route('admin.users.destroy', $user->user_id) }}" method="POST"
style="display: none">
#csrf
#method("DELETE")
</form>
</td>
</tr>
#endforeach
#endcan
Output :

So after a couple of days of debugging, I realized that my teams() method should be team() inside the User model as the user has only one team and BelongsTo relation will only return one record.
Credits: https://www.reddit.com/r/laravel/comments/ldvtgd/custom_admin_gate_not_working/
https://laracasts.com/discuss/channels/laravel/admin-gate-not-working?page=1#reply=687840
Here are the changes :
User.php
public function team()
{
return $this->belongsTo(Team::class);
}
/**
* Check if the user belongs to Admin Team
* #param string $team
* #return bool
*/
public function isAdmin(string $team)
{
return $this->team()->where('name', $team)->exists();
}
AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Gate::define('is-admin', function (User $user){
return $user->isAdmin('Admin');
});
}
UserController.php
public function index()
{
if (Gate::allows('is-admin')) {
return view('admin.users.index', ['users' => User::paginate(10)]);
}
dd('you need to be admin!');
}

Related

Trying to get property 'id' of non-object (View: /home/alex/Desktop/laravel/cms/resources/views/posts/index.blade.php)

i found out that these 2 lines cause the problem, but i don't know how to rewrite them to proceed
<a href="{{ route('categories.edit', $post->category->id ) }}">
{{ $post->category->name }}
</a>
Here is my posts/index.blade.php
#extends('layouts.app')
#section('content')
<div class="d-flex justify-content-end mb-2">
Add Post
</div>
<div class="card card-default">
<div class="card-header">Posts</div>
<div class="card-body">
#if ($posts->count()>0)
<table class="table">
<thead>
<th>Image</th>
<th>Title</th>
<th>Category</th>
<th></th>
<th></th>
<tbody>
#foreach($posts as $post)
<tr>
<td>
<img src="{{ asset('storage/'.$post->image) }}" width="120px" height="60px" alt="">
</td>
<td>
{{ $post->title }}
</td>
<td>
<a href="{{ route('categories.edit', $post->category->id ) }}">
{{ $post->category->name }}
</a>
</td>
#if($post->trashed())
<td>
<form action="{{ route('restore-posts', ['post' => $post['id']]) }}" method="POST">
#csrf
#method('PUT')
<button type="submit" class="btn btn-info btn-sm">Restore</button>
</form>
</td>
#else
<td>
Edit
</td>
#endif
<td>
<form action="{{ route('posts.destroy', ['post' => $post['id']]) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</thead>
</table>
#else
<h3 class="text-center">
No Posts Yet
</h3>
#endif
</div>
</div>
#endsection
and here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\Posts\CreatePostRequest;
use App\Post;
use App\Category;
// use Illuminate\Support\Facades\Storage;
use App\Http\Requests\Posts\UpdatePostRequest;
class PostsController extends Controller
{
public function __construct(){
$this->middleware('verifyCategoriesCount')->only(['create','store']);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('posts.index')->with('posts', Post::all());
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create')->with('categories', Category::all());
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$image = $request->image->store('posts');
Post::create([
'title' => $request->title,
'description' => $request->description,
'content' => $request->content,
'image' => $image,
'published_at' => $request->published_at,
'category_id' => $request->category
]);
session()->flash('success', 'Post created succesfully.');
return redirect(route('posts.index'));
}
/**
* 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(Post $post)
{
return view('posts.create')->with('post', $post)->with('categories', Category::all());
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(UpdatePostRequest $request, Post $post)
{
$data = $request->only(['title', 'description', 'published_at', 'content']);
// check if new image
if($request->hasFile('image')){
// upload it
$image = $request->image->store('posts');
// delete old one
$post->deleteImage();
$data['image'] = $image;
}
// update attributes
$post->update($data);
// falsh message
session()->flash('success', 'Post updated succesfully');
// redirect user
return redirect(route('posts.index'));
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
if($post->trashed()){
$post->deleteImage();
$post->forceDelete();
}else{
$post->delete();
}
session()->flash('success', 'Post deleted succesfully.');
return redirect(route('posts.index'));
}
/**
* Display a list of all trashed posts
*
* #return \Illuminate\Http\Response
*/
public function trashed(){
$trashed = Post::onlyTrashed()->get();
return view('posts.index')->withPosts($trashed);
}
public function restore($id){
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
$post->restore();
session()->flash('success', 'Post restored succesfully');
return redirect()->back();
}
}
Your $post->category is not an object which is why this error is coming.
Try
dd($post->category)
and you'll see what's in it. That will help you to debug the real problem.
First eager load the relation (to prevent N+1 issues) using:
public function index()
{
$posts = Post::with('category')->get();
return view('posts.index')->with('posts', $posts);
}
Then if you still get the error, it might be due to the fact that the post you are trying to view does not have category, so the relation is null. So when you try to get the category id, it throws that exception that null does not have id.
You can simply solve it by checking if there is any category before:
#if($post->category)
<a href="{{ route('categories.edit', $post->category->id ) }}">
{{ $post->category->name }}
</a>
#endif
Use eager loading in your controller before injecting the model to the view.
$post->load('category');
Make sure that each post has a relation with a category.

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$event_parts

I received this error while trying to run two-layer loops in order to get a list out of an array:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$event_parts
I wanted to produce a table where it lists all my events and at the same time there is a column that listed all the attending participants.
Here is the phpmyadmin table:
Here is my EventController:
<?php
namespace App\Http\Controllers;
use App\Models\Event;
use Illuminate\Http\Request;
class EventController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$events = Event::paginate(5);
return view('events.index', compact('events'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$events = Event::all();
return view('events.create', compact('events'));
##return view('events.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'event_name' => 'required',
'event_start' => 'required',
'event_end' => 'required',
'event_category' => 'required',
#'event_part' => 'required'
]);
Event::create($request->all());
return redirect()->route('events.index')
->with('success', 'Event added successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function show(Event $event)
{
return view('events.show', compact('event'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function edit(Event $event)
{
return view('events.edit', compact('event'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Event $event)
{
$request->validate([
'event_name' => 'required',
'event_start' => 'required',
'event_end' => 'required',
'event_category' => 'required'
]);
$event->update($request->all());
return redirect()->route('events.index')
->with('success', 'Event updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function destroy(Event $event)
{
$event->delete();
return redirect()->route('events.index')
->with('success', 'Event deleted successfully');
}
}
Here is my migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEventsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->id('event_id');
$table->string('event_name');
$table->datetime('event_start');
$table->datetime('event_end');
$table->string('event_category');
$table->json('event_parts')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('events');
}
}
Here is my index.blade.php:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD </h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('events.create') }}" title="Create a event"> <i class="fas fa-plus-circle"></i>
</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered table-responsive-lg">
<tr>
<th>No</th>
<th>Event Name</th>
<th>Event Start</th>
<th>Event End</th>
<th>Event Category</th>
<th>Event Participants</th>
<th width="280px">Action</th>
</tr>
#foreach ($events as $event )
<tr>
<td>{{ ++$i }}</td>
<td>{{ $event->event_name }}</td>
<td>{{ $event->event_start }}</td>
<td>{{ $event->event_end }}</td>
<td>{{ $event->event_category }}</td>
<td> #foreach ($events->event_parts as $event_part) {{ $event_part }} #endforeach</td>
<td>
<form action="{{ route('events.destroy', $event->event_id) }}" method="POST">
<a href="{{ route('events.show', $event->event_id) }}" title="show">
<i class="fas fa-eye text-success fa-lg">View</i>
</a>
<a href="{{ route('events.edit', $event->event_id) }}">
<i class="fas fa-edit fa-lg">Edit</i>
</a>
#csrf
#method('DELETE')
<button type="submit" title="delete" style="border: none; background-color:transparent;">
<i class="fas fa-trash fa-lg text-danger">Delete</i>
</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $events->links() !!}
#endsection

Laravel 7. How to fetch records from various tables using foreign key in laravel?

Laravel 7 and 2 tables: comp, computers.
I would like to display in the view index.blade.php the name of the computer e.g. DELL, IBM, LENOWO instead of id of this name.
What the foreach syntax should look like to retrieve the computer name from the computers table.
And when you add a new PC, what should the dropdownlist look like?
class CreateCompTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('comp', function (Blueprint $table) {
$table->id();
$table->integer('name_id')->unsigned();
$table->string('number');
$table->string('year');
$table->timestamps();
$table->foreign('name_id')->references('id')->on('computers')
->onDelete('cascade');
});
}
Table Computers
class CreateComputersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('computers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
CompControllers
namespace App\Http\Controllers;
use App\Comp;
use Illuminate\Http\Request;
class CompController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$comp = Comp::latest()->paginate(5);
return view('comp.index',compact('comp'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('comp.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name_id' => 'required',
'number' => 'required',
'year' => 'required',
]);
comp::create($request->all());
return redirect()->route('comp.index')
->with('success','xxx.');
}
/**
* Display the specified resource.
*
* #param \App\Comp $comp
* #return \Illuminate\Http\Response
*/
public function show(Comp $comp)
{
return view('comp.show',compact('comp'));
}
View index.blade.php
#extends('comp.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Comp</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('comp.create') }}"> Add comp</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>L.p</th>
<th>Name comp</th>
<th>Number comp</th>
<th>Year</th>
<th width="250px">Acction</th>
</tr>
#foreach ($comp as $comp)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $comp->name_id }}</td>
<td>{{ $comp->number }}</td>
<td>{{ $comp->year }}</td>
<td>
<form action="{{ route('comp.destroy',$comp->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('comp.show',$comp->id) }}">View</a>
<a class="btn btn-primary" href="{{ route('comp.edit',$comp->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endsection
On Comp model, make a belongsTo relation :
public function computer()
{
return $this->belongsTo('App\Computer', 'name_id');
}
Now you can access this relation, from your blade, as:
#foreach($comp as $comp)
<tr>
<td>{{ $comp->computer->name }}</td>
</tr>
#endforeach

laravel trashed method does not exist

I'm on the project in which I want to get the table in which record which I was trashed show and its working correctly and my trashed records are also show.
My logic of code is that when my trashed record are shown then in action field it show me only restore button otherwise in that field it show me two button of 'Delete' and 'Trash'. for this to work, when I apply this condition in my view file its return me this error which written in my title. #if($record->trashed())
resource controller
namespace App\Http\Controllers;
use App\sepCategory; use Illuminate\Http\Request;
class SepCategoryController extends Controller {
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$cat=sepCategory::all();
return view('cusCate',compact('cat'));
}
/**
* 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\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function show(sepCategory $sepCategory)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function edit(sepCategory $sepCategory , $id)
{
$a= sepCategory::find($id);
return view('cusEdit',['data'=>$a]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function update(Request $request, sepCategory $sepCategory)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function destroy(sepCategory $sepCategory,$id)
{
if ($sepCategory::find($id)->forceDelete()) {
return back()->with('message','record successfully delete');
} else {
return back()->with('error','record not delete');
}
}
public function trash()
{
$cat=sepCategory::onlyTrashed()->paginate(3);
return view('cusCate',compact('cat'));
}
public function remove($id)
{
$temp= sepCategory::find($id);
if ($temp->delete()) {
return back()->with('message','record successfully trashed');
}else{
return back()->with('error','can not correctly trashed');
}
}
public function recover($id)
{
} }
view blade file
view the trashed data
Category of student
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#elseif(session()->has('error'))
<div class="alert alert-danger">
{{ session()->get('error') }}
</div>
#else
#endif
<table>
<tr>
<th>Name</th>
<th>id</th>
<th>Phone</th>
<th>Roll no</th>
<th>Action</th>
<th>
#if ($cat->trashed())
Deleted At
#else
updated At
#endif
</th>
</tr>
#if (isset($cat))
#foreach ($cat as $item)
<tr>
<td>{{ $item->name }}</td>
<td>{{ $item->id }}</td>
<td>{{ $item->mobile_no }}</td>
<td>{{ $item->roll_no }}</td>
<td>
#if ($item->trashed())
Restore
#else
Edit
<form action="{{ url('/home/destroy') }}" method="post">
#csrf
{{ method_field('DELETE') }}
<input type="hidden" value="{{ $item->id }}" name="id">
<button type="submit">Delete</button>
</form>
<!-- this is trashed-->
Trashed
#endif
</td>
<td>
#if ($item->trashed())
{{ $item->deleted_at }}
#else
{{ $item->updated_at }}
#endif
</td>
</tr>
#endforeach
#endif
Error
Method Illuminate\Database\Eloquent\Collection::trashed does not exist. (View: D:\xamp\htdocs\project laravel\newTran\resources\views\cusCate.blade.php)
why it say trashed not exist
To begin with.. the trashed() method is avaiable if you are using the withTrashed() scope when doing your query. So, you'll need to add this (also notice that I replaced all() with get()):
# SepCategoryController.php
$cat = sepCategory::withTrashed()->get();
// ^^^^^^^^^^^^^^^^^^^^
return view('cusCate', compact('cat'));
Notice that this model must use the SoftDeletes trait.
Now, you are calling the trash() method on a Collection instance instead of on a model one. This is because $cat is a collection of sepCategory:
# SepCategoryController.php
$cat = sepCategory::withTrashed()->get();
return view('cusCate', compact('cat'));
<!-- In your view -->
<th>
#if ($cat->trashed()) // <---
Deleted At
#else
updated At
#endif
</th>
You should iterate over the elements of this collection in order to access individual models:
#foreach($cat as $category)
<th>
#if ($category->trashed()) // <---
Deleted At
#else
updated At
#endif
</th>
#endforeach

Laravel Delete not working

As the title suggests, I can't get the delete() option to work. I've struggled through a lot of posts online but the right answer just isn't there.
I'm using Laravel 5.5 with Homestead (installed a week ago, newest versions or so).
Let me give you some code and I really hope somebody is able to help me out.
This gives me a headache and the olanzapine is running out. Please tell me what I am doing wrong, and if there is something that's missing, please let me know!
I want to delete a page as a admin, but I Laravel doesn't seem to authorize me and gives me this error:
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
This is my controller:
<?php
namespace App\Http\Controllers\Admin;
use Auth;
use App\Page;
use App\Http\Requests\WorkWithPage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PagesController extends Controller
{
public function __construct() {
$this->middleware('admin');
$this->middleware('can:manageUsers,App\User');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (Auth::user()->isAdmin()) {
$pages = Page::paginate(20);
} else {
$page = Auth::user()->pages()->paginate(5);
}
return view('admin.pages.index', ['pages' => $pages]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.pages.create')->with(['model' => new Page()]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(WorkWithPage $request)
{
Auth::user()->pages()->save(new Page($request->only([
'title','url','content'])));
return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangemaakt');
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Page $page
* #return \Illuminate\Http\Response
*/
public function edit(Page $page)
{
if(Auth::user()->cant('update', $page)){
return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangepast');
}
return view('admin.pages.edit', ['model' => $page]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Page $page
* #return \Illuminate\Http\Response
*/
public function update(WorkWithPage $request, Page $page)
{
if(Auth::user()->cant('update', $page)){
return redirect()->route('pages.index')->with('status', 'Dat mag jij niet');
}
$page->fill($request->only([
'title','url','content'
]));
$page->save();
return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangepast');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Page $page
* #return \Illuminate\Http\Response
*/
public function destroy(Page $page)
{
if(Auth::user()->cant('delete', $page)){
return redirect()->route('pages.index')->with('status', 'Hey knul! Pssst! Wegwezen!');
}
$page->id->delete();
return redirect()->route('pages.index')->with('status', 'Page has been deleted.');
}
}
And this is my index page (index as in admin index for backend :
#extends('layouts.app') #section('content')
<div class="container">
#if (session('status'))
<div class="alert alert-info">
{{ session('status') }}
</div>
#endif
Nieuwe pagina
<br>
<br>
<table class="table">
<thead>
<tr>
<th>Naam</th>
<th>URL</th>
<th>Opties</th>
</tr>
</thead>
#foreach($pages as $page)
<tr>
<td>
{{ $page->title }}
</td>
<td>{{ $page->url }}</td>
<td class="text-right">
<a href="{{ route('pages.destroy', ['page' => $page->id])}}" class="btn btn-danger delete-link" data-message="Are you sure you want to delete this page?"
data-form="delete-form">
Delete
</a>
</td>
</tr>
#endforeach
</table>
{{$pages->links()}}
</div>
<form id="delete-form" action="" methode="POST">
{{method_field('DELETE')}}
{!! csrf_field() !!}
</form>
#endsection
Then there the routes:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/admin', function() {
return view('admin.index');
})->middleware('admin');
Route::resource('/admin/pages', 'Admin\PagesController', ['except' => ['show']]);
Route::resource('/admin/blog', 'Admin\BlogController', ['except' => ['show']]);
Route::resource('/admin/users', 'Admin\UsersController', ['except' => ['create', 'store', '']]);
Route::get('/home', 'HomeController#index')->name('home');
Then the policy:
<?php
namespace App\Policies;
use App\User;
use App\Page;
use Illuminate\Auth\Access\HandlesAuthorization;
class PagePolicy
{
use HandlesAuthorization;
public function before($user, $ability) {
if ($user->isAdmin()) {
return true;
}
}
/**
* Determine whether the user can update the page.
*
* #param \App\User $user
* #param \App\Page $page
* #return mixed
*/
public function update(User $user, Page $page)
{
return $user->id = $page->user_id;
}
/**
* Determine whether the user can delete the page.
*
* #param \App\User $user
* #param \App\Page $page
* #return mixed
*/
public function delete(User $user, Page $page)
{
return $user->id = $page->user_id;
}
}
And finally the middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AccessAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->hasAnyRole(['Super Admin','Admin'])) {
return $next($request);
}
return redirect('login');
}
}
Update: fixed!
In the view I changed:
#foreach($model as $post)
<tr>
<td>
{{ $post->title }}
</td>
<td>{{ $post->user()->first()->name }}</td>
<td>{{ $post->slug }}</td>
<td class="text-right">
<a href="{{ route('blog.destroy', ['blog' => $post->id])}}" class="btn btn-danger delete-link" data-message="Are you sure you want to delete this page?"
data-form="delete-form">
Delete
</a>
</td>
</tr>
#endforeach
</table>
{{$model->links()}}
</div>
<form id="delete-form" action="#" methode="POST">
{{ method_field('DELETE') }}
{!! csrf_field() !!}
</form>
To:
#foreach($pages as $page)
<tr>
<td>
{{ $page->title }}
</td>
<td>{{ $page->url }}</td>
<td class="text-right">
<form action="{{ route('pages.destroy', ['page' => $page->id]) }}" method="POST" class="btn btn-danger delete-link" >
<input type="submit" value="delete"/>
{{method_field('DELETE')}}
{!! csrf_field() !!}
</form>
</td>
</tr>
#endforeach
</table>
{{$pages->links()}}
Not sure where to start...
First the exception you are receiving is because you are sending wrong method to the url. (I never do it that way) but probably you are sending GET when you are expecting POST (with DELETE overwrite). You have wrong named "methode", it should be "method".
Next... not sure if this is gone work $page->id->delete();... maybe $page->delete().
As suggestion - maybe it will be better to use !can() instead of cant(). There is no difference, but cant() may confuse you in some point.
And I am glad to see someone using ->fill() method but you may come up on a small problem when dealing with checkboxes. Check this: https://github.com/LaraModulus/admin-core/blob/master/src/traits/HelpersTrait.php

Categories