Currently I have users.index blade which I would like to restrict. However, I failed to restrict it.
I have tried to create another test blade and a TestController and I have set permission to it and it works fine.
However with UserController, there is just no way to restrict Users from accessing it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
class TestController extends Controller
{
/**
* Restricting pages
*/
public function __construct()
{
$this -> middleware('permission:test-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('test.index');
}
/**
* 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($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)
{
//
}
}
views/test/index.blade.php
#extends('layouts.app')
#section('content')
<p>Testing Page</p>
#endsection
These are the results if I don't permit a particular user role to access this page.
enter image description here
enter image description here
So the above is the correct behavior.
However when it comes to user.index , I applied the same technique in the constructor of the UserController but it doesn't work
app/Http/Controllers/UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller
{
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC') -> paginate(5);
return view('users.index' , compact('data')) -> with('i' , ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('name','name') -> all();
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request -> all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('name','name') -> all();
$userRole = $user->roles -> pluck('name','name') -> all();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this -> validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if( ! empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user -> update($input);
DB::table('model_has_roles') -> where('model_id',$id) -> delete();
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id) -> delete();
return redirect() -> route('users.index') -> with('success','User deleted successfully');
}
}
Result [I am still able to view this Blade in front end despite not having the permission to view this page]
enter image description here
This is my role-has-permission tablerole-has-permission
This is my role table
role
This is my permission table
permissions
This is my model-has-roles table model-has-roles
This is my model-has-permissions table model-has-permissions
If you want to restrict specific routes or all you can do something like this:
Route::middleware(['auth', 'permission:user-list'])->group(function (){
Route::get('/create', 'WelcomeController#create')->name('welcome');
...
...
..
});
or you can replace
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
to
public function construct()
{
$this -> middleware('permission:user-list')->except(['index']);
}
Related
Controller name MyController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MyController 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(){
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request){
//
$request->session()->put('key', '123');
$data = $request->session()->get('key');
print_r($data);
}
/**
* 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){
//
}
public function contact(){
return view('contact');
}
public function createSession(Request $request){
//
$request->session()->put('key', '123');
$data = $request->session()->get('key');
print_r($data);
}
public function viewSession_v1(Request $request){
$data = $request->session()->get('key');
print_r($data);
}
public function viewSession_v2(Request $request){
$data = $request->session()->get('key');
print_r($data);
}
}
Route:
Route::get('createSession', 'MyController#createSession');
Route::get('viewSession-1', 'MyController#viewSession_v1');
Route::get('viewSession-2', 'MyController#viewSession_v2');
Now when I call "createSession" it will create new session and when i call either "viewSession-1" or "viewSession-2" it will display session value but I want to remove Request $request from viewSession_v2() so I did following code:
public function viewSession_v2(){
$request = new \Illuminate\Http\Request();
$data = $request->session()->get('key');
print_r($data);
}
Now when I call "viewSession-2" it will give me following error
Please anyone can tell me how can I create request object in method/function? and why it gives me an error here?
You always have access to the request() and session() helpers:
public function viewSession_v2(){
$data = request()->session()->get('key');
print_r($data);
}
or
public function viewSession_v2(){
$data = session()->get('key');
print_r($data);
}
As we know Laravel provides web middleware concepts. I think you should use to remove the session request.
Route::group(['middleware' => ['web']], function () {
// your routes here
});
More Info
Or you can put this condition as:
public function viewSession_v2(Request $request){
if($request->hasSession()) {
$data = $request->session()->get('key');
print_r($data);
}
}
I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use DB;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC')->paginate(5);
return view('users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('display_name','id');
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.
I created a resource BrandController and then made its routes. The problem is that some routes are working and some are not. For example, create route is not working. I have also tried it to declare routes manually but problem is same. I ran command like
php artisan route:clear
php artisan cache:clear
Here are routes
Route::group(['namespace' => 'AppControllers'], function () {
/*
|--------------------------------------------------------------------------
| All routes of BrandController are defined here
|--------------------------------------------------------------------------
|
*/
Route::get('brands', 'BrandController#index')->name('brand.index');
Route::get('brand/create', 'BrandController#create')->name('brand.create');
Route::get('brand/edit/{id}', 'BrandController#edit')->name('brand.edit');
Route::delete('brand/delete/{id}', 'BrandController#destroy')->name('brand.destroy');
Route::post('brand/store', 'BrandController#store')->name('brand.store');
Route::post('brand/update/{id}', 'BrandController#update')->name('brand.update');
// Here is resource route
Route::resource('brands', 'BrandController');
});
I have created a simple a tag here it is:
Add New
Whenever I click on this link it converts / into dotlike this
http://localhost:8080/rms/public/brands.create
It also generated
http://localhost:8080/rms/public/brand/create
But same issue persists. NotFoundHttpException in RouteCollection
Controller Code:
<?php
namespace App\Http\Controllers\AppControllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Brand;
class BrandController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//dd('jgh');
//$brands = brand::all();
return view('brands.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return redirect('brands.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(BrandRequest $request)
{
$input = $request->all();
$storeBrand = new Brand();
$storeBrand->create($input);
//return redirect->()->back();
}
/**
* 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)
{
$editBrand = Brand::findOrFail($id);
return view('brands.edit',compact('editBrand'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(BrandRequest $request, $id)
{
$updateBrand = Brand::findOrFail($id);
$input = $request->all();
$updateBrand->update($input);
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$deleteBrand = Brand::findOrFail($id);
$deleteBrand->delete();
return redirect()->back();
}
}
Change your create method like below
public function create()
{
return redirect('brands/create');
}
. notation not works in redirect method...
Make your resource routes like this
Route::resource('brand', 'BrandController', [
'names' => [
'index'=>'brand.list',
'create'=>'brand.create',
'store'=>'brand.store',
'update'=>'brand.update',
'edit'=>'brand.edit',
'show'=>'brand.show',
'destroy'=>'brand.remove',
]
]);
Your can use:
public function create()
{
return redirect()->route('brands.create');
}
Or
public function create()
{
return redirect('brands/create');
}
But I am suggesting you use the first one because in that we are using route name in that. if you want to change url them you don't have to worry about this code.
i am a new laravel user and a have admin page which doing update delete and insert my problem is i dont know how to call this functions in route.
Note: all this options working on one page (admin).
so please can anyone help me ?!
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
class BlogPostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(){
$date = date('Y-m-d');
$time = time('H:i:s');
/*$sections = ['History' => 'history.png','Electronics' => 'electronics.png','Electrical' => 'electrical.png','Science' => 'science.png',
'Art'=>'ARt.png','Database'=>'database.png','Irrigation'=>'irrigation.png','Novel'=>'Novel.png','Style'=>'Stsyle.png'];
*/
$sections = DB ::table('sections')->get();
return view('libraryViewsContainer.library')->withSections($sections)->withDate($date)->withTime($time);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create(){
//return View::make('posts.create');
return '<center><h1>Creating new section in the library!</h1></center>';
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store( Request $request){
$section_name = $request->input('section_name');
$file = $request->file('image');
$destinationPath = 'images';
$filename = $file->getClientOriginalName();
$file->move($destinationPath,$filename);
DB ::table('sections')->insert(['section_name'=>$section_name,'image_name'=>$filename]);
return redirect('admin');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id){
// $post = Post::find($id);
// return View::make('posts.show')->with('post', $post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id){
// $post = Post::find($id);
// return View::make('posts.edit')->with('post', $post);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id,Request $request){
$section_name = $request->input('section_name');
DB ::table('sections')->where('id',$id)->update(['section_name'=>$section_name]);
return redirect('admin');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id){
DB :: table('sections')->where('id',$id)->delete();
return redirect('admin');
}
public function admin()
{
$sections = DB ::table('sections')->get();
return view('libraryViewsContainer.admin',['sections'=>$sections]);
}
}
Not entirely sure of the question, but you list the routes in routes.php, under the web group (so it applies default checks).
When you have resources, they'll use CRUD operations (create, read, update, delete) and will correspond to the default operates in the class. Else, make your own function names, and put seperate routes.
Route::group(['middleware' => ['web', 'auth']], function () {
Route::resource('/user', 'UserController');
}
Another option is calling the method direct in your routes:
Route::get('/auth/login', '\App\Http\Controllers\Auth\AuthController#getLogin');
Route::any('/datafeed/{id}/validate', 'DataFeedController#validateQuery');
You'll notice {id} which is the variable available in the function you've selected i.e. function validateQuery($id);
Here's a full example:
class UserController extends BaseController
{
public function __construct(User $model)
{
parent::__construct($model);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$collection = $this->model->all();
return view('user.index')->with('collection', $collection);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('user.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = Input::except(['_method', '_token']);
$connector = $this->model->create($input);
return redirect()->action('UserController#show', [$connector->id]);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$connector = $this->model->findOrFail($id);
return view('user.show')->with('connector', $connector);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$connector = $this->model->findOrFail($id);
return view('user.edit')->with('connector', $connector);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$input = Input::except(['_method', '_token']);
$connector = $this->model->findOrFail($id);
$connector->update($input);
return redirect()->action('UserController#show', [$id]);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$currentID = Auth::user();
$user = $this->model->findOrFail($id);
if ($currentID->id != $user->id) {
$user->delete();
} else {
Session::flash('flash_message', "You cant delete your own account!");
Session::flash('flash_type', 'alert-danger');
}
return redirect()->action('UserController#index');
}
And another example with a custom route:
Route::any('/datafeed/{id}/execute', 'DataFeedController#execute');
public function execute($id, $test = false) {
$results = $this->executeQuery($id, $test);
return view('datafeed.execute')->with('results', $results);
}
I'm not entirely sure on your plans (or even if you've fully read the documentation?) but you can access these functions by doing something similar to the following in your routes.php or Routes\web.php (depending on your version) file:
Route::get('/blog/create', 'BlogPostController#create');
Route::get('/blog/article/{id}', 'BlogPostController#show');
The first part is defining the route and the second part is saying what method should be run on the defined controller when this route is matched in the address bar. It doesn't always have to be get requests though, you can do get, post, patch and put
in App/Abstracts/ folder I have following file
1.Transformer.php
<?php
namespace App\Abstracts;
use eventsTransformer;
abstract class Transformer
{
public function transformCollection(array $item)
{
return array_map([$this ,'transform'],$item->toArray());
}
public abstract function transform($event);
}
2.eventsTransformer
<?php
namespace App\Abstracts;
class EventTransformer extends Transformer
{
public function transform($event)
{
return [
'event'=> $event['event'],
'date' => $event['date'],
'e_code'=> $event['eventcode'],
'country'=> $event['country'],
'city'=> $event['city']
];
}
}
Now In my Controller I am using them like this
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\ResponseFactory;
use App\Abstracts\eventsTransformer;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Event;
class EventsapiController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
//use EventTransformer;
protected $eventTransformer;
public function __construct(EventTransformer $EventTransformer){
$this->$eventTransformer = $EventTransformer; // replace 'collector' with whatever role you need.
}
public function index()
{
//
$events = Event::All();
$response = array();
return response()->json([
'data'=>$this->eventTransformer->transform($events)
],200);
//return $response['data']=$events;
}
/**
* 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($id)
{
//
$event = Event::find($id);
if(!$event)
{
return response()->json([
'error'=> 'Event does not exist',
'code' => 'e101'
],404);
}
return response()->json([
'data'=>$event->toArray()
],200);
}
/**
* 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 am getting following error
ReflectionException in Container.php line 790: Class App\Http\Controllers\EventTransformer does not exist
Can any one help me out with this
MyQuestion is the same what How to include abstract in Laravel5
Thanks
You are getting this error because you misspelled namespace.
Instead of:
use App\Abstracts\eventsTransformer;
you should use:
use App\Abstracts\EventTransformer;
in your EventsapiController