how to pass variable to routes in laravel? - php

So i have a variable in my routes.php and i want to pass it to the route::get, this is my code for more details :
$user = User::find(Auth::user()->username);
Route::get('/services/here i want to put my variable', 'ServiceController#show');
so please if someone has any idea i will be very appreciative

The problem with variating your routes with something like:
$user = User::find(Auth::user()->username);
Route::get("/services/$user->username", 'ServiceController#show');
Is that you may enconter some problems in cases where the user does't exists. If you do that and go to your command line and execute:
php artisan routes
There will be no logged user so that route will be pointed to /services/. What you have to do to prevent those cases is to create a filter and process your route on it:
The route:
Route::get("/services/{username}", array('before' => 'user-must-be-logged-in', 'uses' => 'ServiceController#show'));
A filter to do some checks on it:
Route::filter('user-must-be-logged-in', function()
{
if ( ! Auth::check())
{
App::abort(404); /// user is not logged in, this route does not exist
}
if ( ! User::where('username', $username)->first() )
{
App::abort(404); /// user does not exists, this route does not exist
}
if (User::where('username', $username)->first()->id !== Auth::user()->id)
{
App::abort(404); /// selected is not the current logged user, this route does not exist
}
});
A controller doing whatever you need with it:
class ServiceController extends Controller {
public function show()
{
$user = User::where('username', $username)->first();
// now do whatever you need with your user;
}
}

assuming its $user you want to put in there
$user = User::find(Auth::user()->username);
Route::get("/services/$user", 'ServiceController#show');
swap single quotes for doubles and pass in your var (either that or drop out of your single quotes concat in with . your var

Related

Laravel 8 gates not working with Auth::guard

Hey I am developing a project where I have roles and permissions for users and I am trying to protect my routes with the help of middleware by defining Gates but it's showing me 403| Not Authorized. I can't understand what the actual problem is?
Into Category Controller
public function addcategory(AdminsRole $adminsroles){
return view('add-category');
}
Into Routes
Route::get('/add-category', [CategoryController::class, 'addcategory'])->middleware('can:add-category')->name('addcategory');
Into AuthServiceProvider.php
$admin = Auth::guard('admin');
Gate::define('add-category', function ($admin, AdminsRole $adminsroles) {
if($admin->user()->u_type != 'superadmin'){
$adminRolescount = $adminsroles::where([
['admin_id', '=', $admin->user()->id],
['module', '=', 'categories'],
['add_access', '=', '1'],
])->count();
return $adminRolescount;
}else{
return $adminRolescount = 1;
}
});
I think what you're looking for can be simplified. The code in your controller and routes file does not need to be adjusted. I would however change your gate definition to the following:
Gate::define('add-category', function ($user = null) {
// Fetch user from custom guard
$user = Auth::guard('admin')->user();
// Check if a valid user instance was passed
if (is_null($user)) {
return false;
}
// Allow super admins to add categories regardless of AdminsRole existence
if ($user->u_type === 'superadmin') {
return true;
}
// Check if current user has a matching AdminsRole row with add_access permission
return AdminsRole::where([
['admin_id', '=', $user->id],
['module', '=', 'categories'],
['add_access', '=', '1'],
])->exists();
});
Note that a gate always receives a user instance as their first parameter if there is a logged in user, you needn't supply this yourself. Additionally, you can query for the AdminsRole existence directly via the model, using the id of the user instance that is being checked and automatically supplied to the gate.

Laravel 7.x Only the profile's Owner and some roles may enter or do action

I'm new at Laravel and I don't quite sure how to get User's session so he can see his own profile but can't be seen by other users except for the Admin role.
this is what I thought
profile/ProfileControllers.php
public function show(User $user)
{
if(Gate::allows('manageUsers')){
return view('Profile.Users.profile')->with([
'user' =>$user,
]);
}
if ($user->id === $user->id) {
return view('Profile.Users.profile')->with([
'user' =>$user,
]);
}
return redirect(route('home'));
}
I thought using $user->id == $user->id means the session user id = this id http://127.0.0.1:8000/profile/users/{id} but it is not and i can see the other user's profiles using a single user.
manageUsers inside the gate is the user admins like (cashier, sales, etc)
I reckon some other methods are using middleware in the web route. But I failed to understand what's to put on my middleware
routes/web.php
Route::namespace('Profile')->prefix('profile')->name('profile.')->middleware('?')->group(function(){
Route::resource('/users', 'ProfilesController', ['except' =>['store', 'create']]);
});
what I'm trying to approach is,
Only the owner of the profile and some roles can see the profile. and the guest will be redirected to home.
maybe you want something like this?
public function show(User $user)
{
if(Gate::allows('manageUsers')){
return view('Profile.Users.profile')->with([
'user' =>$user,
]);
}
if (auth()->user()->id === $user->id) {
return view('Profile.Users.profile')->with([
'user' =>$user,
]);
}
return redirect(route('home'));
}
Try $user->id == auth()->id()
You can create your own middleware and put your login theri.
php artisan make:middleware IsAdmin
Then register this to Kernel.php file
Inside middleware
If(auth()->user()->type == 'Admin'){
//Ruj your script inside if block , and instead of attribute TYPE
//you must put what you have used in databse to check if user
//is admin or not.
}

How to prevent get/post clash in Laravel 6?

Currently I'm working on a project where I made it so that when a user types a correct password in form field, it will give them the items from the given section.
The main problem i'm having is that to do this I need to capture the request and therefore the route has to be a post method instead of a get as such:
public function index(Request $request)
{
$id = $request->input('id');
$password = $request->input('password');
$result = DB::table('scrumboards')->find($id);
if ($result->key == $password) {
$scrumboard = $result;
$items = DB::table('backlogs')->get();
return view('scrumboard', ['items' => $items, 'scrumboard' => $scrumboard]);
} else {
$scrumboard = $result;
return redirect('home');
}
}
and the route as such:
Route::post('/scrumboard', 'ScrumboardController#index');
By doing this, request errors wont work since It wants to redirect back but can't since this is a post method.
Any way I can avoid this clash?
Routes can have multiple HTTP verbs. Define your route as
Route::match(['get', 'post'], '/scrumboard', 'ScrumboardController#index');
to make it available as GET and POST route.

Laravel Access Control with Model Objects

I need to restrict the access to some parts of the application depending on the user logged in. I mean for example to let a user edit only its own posts on a blog application.
Is there a better approach than in every function of the controller, if the user is not the owner of the required post, redirect to some error page?
For example if my routes are /post/{post_id}/edit, /post/{post_id}/preview, /post/{post_id}/delete, can I somehow declare a general function in the PostController like:
if(Post::find($post_id)->user_id != Auth::user()->id){
return View::make('access-error');
}
Thanks!
In your controller you can do something like this:
public $check = ['edit', 'preview', 'delete'];
public function callAction($method, $parameters) {
if(in_array($method, $this->check, true) &&
$post_id = $parameters['post_id'] &&
Post::find($post_id)->user_id != Auth::user()->id) {
return View::make('access-error');
}
return parent::callAction($method, $parameters);
}
You could throw a 401 error and catch it elsewhere to display a custom page
App::abort(401);
http://laravel.com/docs/4.2/errors#handling-404-errors

How to implement user permissions in Laravel 4?

What I basically want is user permissions.
I've got an table called 'accounts' in my database. There is a column called 'group_id'.
I want to set it when the 'group_id' = 3, then the user is admin. Then he can view special sites, buttons, and things like that. I've tried to implement something like that:
public function ($roleName) {
$role = $this->roles;
if ($role->name == $roleName) {
return true;
}
return false;
}
Also, I don't know what and how the model is needed, do I need an new one and things like that.
Old post, but maybe someone will find this useful
Add a method to your User model that returns true if the user is an admin. In our case here, it's simply "is our group_id equal to 3?"
// models/User.php
class User extends Eloquent
{
...
public function isAdmin()
{
return $this->group_id == 3;
}
}
Next add a filter that can be used to protect routes
// filters.php
Route::filter('admin', function($route, $request)
{
if ( ! Auth::user()->isAdmin())
{
return App::abort(401, 'You are not authorized.');
}
});
Finally use the filter to protect a group of routes. I this simplified case, only an admin user could access /admin
// routes.php
Route::group(array('before' => array('auth|admin')), function()
{
Route::get('/admin', function()
{
return Response::make("You're an admin!");
}
});
Based on this post:
http://laravelsnippets.com/snippets/admin-route-filter
I suggest Authority for Laravel 4
I personally use Verify package for user management.

Categories