improve if else conditions in Laravel - laravel

I have a Laravel Project which is about to go Live in like two days.
I have a lot of quires running in backend and on frontend. I am working on improving speed of application as there will be lot more users in live production.
In my controllers I used this code a lot.
public function createCutting()
{
if (Auth::user()->admin == 0 && Auth::user()->roles()>first()>pivot->role_id == 7)
{
$type_of_cuts = Type::where('field', 2)->get();
$type_of_damages = Type::where('field', 3)->get();
$number_of_boxes = Type::where('field', 4)->get();
$size_of_boxes = Type::where('field', 5)->get();
return view('web.cutting.working_orders.create', compact('type_of_cuts', 'type_of_damages', 'number_of_boxes', 'size_of_boxes'));
} else {
return redirect()->route('working.orders.index')->with('alert', 'You cannot access this page');
}
and blade view is this
#if ($admin != 1)
#if ($role_id == 7)
<a href="{{ route('cutting.working.orders.create') }}" class="btn btn-label-brand btn-bold">
<i class="la la-plus"></i> Create Cutting</a>
#endif
#if ($role_id == 6)
<a href="{{ route('packaging.working.orders.create') }}" class="btn btn-label-brand btn-bold">
<i class="la la-plus"></i> Create Packaging</a>
#endif
#endif
#endif
have a look at if condition in code I have to use it on two places first in controller and then on front-end (to hide links this method in controller).
Is there a better way to use condition in one place and not running same queries twice in app? Maybe like using middleware or so.
Regards,

What you are trying to do is the mixture of magic numbers and verbosity programming.
This is your code:
#if ($admin != 1)
#if ($role_id == 7)
<a href="{{ route('cutting.working.orders.create') }}" class="btn btn-
label-brand btn-bold">
<i class="la la-plus"></i> Create Cutting</a>
#endif
#if ($role_id == 6)
<a href="{{ route('packaging.working.orders.create') }}" class="btn btn-
label-brand btn-bold">
<i class="la la-plus"></i> Create Packaging</a>
#endif
#endif
#endif
You should have used Spatie Blade Directives like so:
//if the user is an admin he/she can perform the action.
#hasrole('admin')
//Granting different admin users different permissions.
#can('create cutting order')
// only the admin who can create cutting...
#endcan
#can('create packaging order')
// only the admin who can create packaging...
#endcan
#else
//he/she is not an admin, then he/she is not allowed to do anything.
#endhasrole

As per the source code you provided, is not about improving if else condition.
You are trying to implement User Access Control by granting privileges to users based on the appropriate roles.
To implement User Access Control regardless whether you're developing a Small Business Application or Enterpise-Level Application, It's not recommended to create your own security for access control. This practice is vunerable to Cross-site request forgery.
The best practice of implementing a User Access Control requires:
Authentication: He/she (user) must provide the Identity on who he/she claims
he/she is. This is typically done by forcing user to provide
his/her username and password in your Login form.
This is already implemented by Laravel using default Laravel
Auth.
Authorization: Here you have to authorize the authenticated users to perform
certain actions based on their respective roles.
This is what is called User Access Control.
As far as security is concerned, you must not implement your own User Access Control. I will recommend you to use Laravel-Permission Package called Spatie which is the best User Access Control for Laravel in my opinion.
It's easy to install and easy to use.
It assigns roles to users
It grants permission to different roles.
Please check the link below for Spatie Official Documentantion and installation's instructions.
https://spatie.be/docs/laravel-permission/v4/installation-laravel
You have to spent time to read documentation carefully so that you cannot miss anything when installing the package.
In adition for Spatie Permission, you can download Admin Panel (GUI) for Spatie Permission created by Laravel Daily using the link below.
https://github.com/LaravelDaily/Laravel-CoreUI-AdminPanel

Related

Trying to show the current signed in users profile. What am i doing wrong | Laravel 9

Trying to show the current signed in user's profile. What am i doing wrong.This is the function on the controller. I'm using Laravel 9
public function show(User $user)
{
return view('users.index', with('user', $user));
}
This is the routes
Route::resource('users', UsersController::class)->middleware('auth');
And my generic layout page
<x-dropdown-item href="/users/{{ auth()->user()->username }}" >Account</x-dropdown-item>
When i click the link i get user not found.
You're utilising route model binding which unless configured otherwise, requires you to provide a route with a model id. You're providing it with a username, so Laravel is throwing a 404 because it can't locate the relevant record in the database.
If you replace username with id, the binding should work.
<x-dropdown-item href="/users/{{ auth()->user()->id }}">
Account
</x-dropdown-item>
The code is fine. Are you sure you have a route with username, resource routes are using id.
To access model like that you need to specify id in the route like:
/users/{id}
However what you are trying to do here is access the logged in user model which you can access with the facade Auth::user();
You can access the user any time any where in the code and there is no need to pass it to an anchor link unless sending to an external system.

Jetstream Browser Sessions does not list devices – Laravel 8

In my dev environment, Log out other browser sessions’ feature works well. However, in the production environment, Log out other browser sessions’ feature doesn’t work. It does not display the devices either.
resources/views/profile/logout-other-browser-sessions-form.blade.php
<x-jet-action-section>
<x-slot name="title">
{{ __('Browser Sessions') }}
</x-slot>
<x-slot name="description">
{{ __('Manage and log out your active sessions on other browsers and devices.') }}
</x-slot>
<x-slot name="content">
<div class="max-w-xl text-sm text-gray-600">
{{ __('If necessary, you may log out of all of your other browser sessions across all of your devices. Some of your recent sessions are listed below; however, this list may not be exhaustive. If you feel your account has been compromised, you should also update your password.') }}
</div>
#if (count($this->sessions) > 0)
There are = {{ count($this->sessions) }}
#else
There are NO sessions
#endif
#if (count($this->sessions) > 0)
...
Dev environment
It shows two devices logged in
Prod environment
There are two devices logged in but it does not show any of them
Does anyone have any idea why this happen?

spatie Call to a member function contains() on null?

I installed the spatie to Laravel permission:
but when I tried to check if the user has rule , this problem appears:
Call to a member function contains() on null?
my code is:
#role('Admin')
<p>This message appears if the user is an admin </p>
#endrole
note: if I check using permission like this:
#can('show-post')
<p>This message appears if the user is an admin </p>
#endcan
it work, why using role doesn't work?

Laravel Authorization can Guest

I am trying to Authorize Guest to show login form if not logged in.
#can('guest')
Let's Start
#endcan
Where do I need to define guest
By default, the Blade templating engine provides so-called authentication directives which determine whether a user is authenticated or not:
#auth
// User is authenticated.
#endauth
#guest
// User is not authenticated.
#endguest
The answer from prd is a very good approach and will work in newer laravel version. (Probably from 5.5)
However if you still want to use can('guest') format, you can do that.
You need to put your custom blade directive in AppServiceProvider.php file and inside boot method.
Blade::if('can', function ($role) {
if($role=='guest'){
return !(auth()->check());
}
// you can also put codes for can('admin') etc
// the return value should be true or false.
});
For more information you can read this.

Laravel csrf-token mismatch

Problem. When I follow an simple authentication tutorial for Laravel (v.5.2), and tries to register a new user I get the error: CSRF-token mismatch.
I am quite new to Laravel, and I am not sure how to proceed.
Background. I crated a new project for the tutorial, and runs it on my local machine (windows 10, on port 8000). I run it with Composer and artisan. My database are also on my local machine with XAMPP (on port 10080).
Code. https://github.com/isak-glans/laravel_problem
The tutorial:
https://www.youtube.com/watch?v=k89EOb9fqa0&list=PL_UnIDIwT95PiPV641VBnEwFAvswNZKuX&index=11
You need to add a cross site request forgery field to your form
<input type="hidden" name="_token" value="{{ csrf_token() }}">
or use the helper method:
{{ csrf_field() }}
This is used to prevent CSRF attacks.
Sorry didn't check your code first.
I cloned the app and registered without problems. I think that you are getting that error because the token expired.
Checkout this thread:
https://laracasts.com/discuss/channels/laravel/csrf-token-mismatch-error-on-session-timeout-form/

Resources