I've done something like this:
web.php
Route::group(['prefix' => {User Role}, 'middleware' => 'AuthUser:superadmin,admindesa'], function() {
Route::get('/', 'DashboardC#index');
Route::get('/penduduk', 'PendudukC#index');
Route::get('/penduduk/{id}/detail', 'PendudukC#detail');
});
Route::group(['prefix' => 'superadmin', 'middleware' => 'AuthUser:superadmin'], function() {
Route::get('/pengguna', 'PenggunaC#index');
Route::get('/pengguna/{id}/edit', 'PenggunaC#edit');
Route::post('/pengguna/{id}/prosesedit', 'PenggunaC#prosesEdit');
Route::get('/pengguna/{id}/hapus', 'PenggunaC#hapus');
Route::post('/ajax/pengguna', 'AjaxC#pengguna');
});
AuthUser.php
class AuthUser
{
public function handle($request, Closure $next, ...$roles)
{
$auth = auth('web')->user();
if (!$auth || !in_array($auth->role, $roles)){
\Session::flash('flash_message', array('pesan' => 'Silahkan login untuk melanjutkan', 'tipe' => 'warning'));
return redirect()->route('login');
}
return $next($request);
}
}
Anyone know what should I write to asign user's role in route prefix? {User Role}
I've found the solution by simply adding role variable to the request
web.php
Route::group(['prefix' => '{role}', 'middleware' => 'AuthUser:superadmin,admindesa'], function() {
Route::get('/', 'DashboardC#index');
Route::get('/penduduk', 'PendudukC#index');
Route::get('/penduduk/{id}/detail', 'PendudukC#detail');
});
Route::group(['prefix' => 'superadmin', 'middleware' => 'AuthUser:superadmin'], function() {
Route::get('/pengguna', 'PenggunaC#index');
Route::get('/pengguna/{id}/edit', 'PenggunaC#edit');
Route::post('/pengguna/{id}/prosesedit', 'PenggunaC#prosesEdit');
Route::get('/pengguna/{id}/hapus', 'PenggunaC#hapus');
Route::post('/ajax/pengguna', 'AjaxC#pengguna');
});
AuthUser.php
class AuthUser
{
public function handle($request, Closure $next, ...$roles)
{
$auth = auth('web')->user();
if (!$auth || !in_array($auth->role, $roles)){
return redirect()->route('login')->with('gagal','Silahkan login untuk melanjutkan');
}
$request->role = $auth->role; // <- this one
return $next($request);
}
}
Everytime you want to get {id} in any controller you HAVE to get {role} too like this:
public function detail(Request $request, $role, $id) // <- this one
{
$penduduk = Penduduk::with(['kabupaten', 'kecamatan', 'kelurahan', 'dusun', 'pendudukjb'])->find($id);
$bantuan = array_column(json_decode($penduduk->pendudukjb, TRUE), 'id_master_jenis_bantuan');
$detail = $request->modal ? '_detail' : 'detail';
return view('penduduk/'.$detail, compact('penduduk', 'bantuan'));
}
Related
I want show domen url user id after signin, example domen/specialist/id.
ALREADY AS DAY 2 IT IS NOT RECEIVED TO DO. Maybe I'm doing something wrong help please.
This my web.php code
// Front End Routes
Route::group([
'namespace' => 'landing',
'middleware' => 'groups',
], function (){
Route::get('/', 'PagesController#index')->name('landing.index');
Route::get('/specialist/{id}', 'SpecialistDashboardController#dashboard')-
>name('frontend.specialist.dashboard');
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
});
Specialist Dashboard Controller code
class SpecialistDashboardController extends Controller
{
public function dashboard($id){
$id = Auth::user()->id;
return view('Frontend.specialists.dashboard.index');
}
public function profile_settings(){
return view('Frontend.specialists.profile_settings.index');
}
}
GroupsMiddleware
public function handle($request, Closure $next)
{
// ADMIN = 5
if (\Auth::check() && Auth::user()->groups == 5){
return $next($request);
}
// PATIENTS = 1
elseif(\Auth::check() && Auth::user()->groups == 1){
return redirect()->route('landing.index');
}
// SPECIALISTS = 3
elseif (\Auth::check() && Auth::user()->groups == 3){
return redirect()->route('frontend.specialist.dashboard');
}
}
Error message:
Missing required parameters for [Route: frontend.specialist.dashboard] [URI: specialist/{id}].
Your frontend.specialist.dashboard route requires a id paramter but you didn't provide any when redirecting. Also looking at your SpecialistDashboardController, the $id can be omitted since you're overwriting it with Auth::id().
Try doing this:
# remove the {id} param
Route::get('/specialist', 'SpecialistDashboardController#dashboard')-
>name('frontend.specialist.dashboard');
class SpecialistDashboardController extends Controller
{
...
public function dashboard(){ // remove the $id param
$id = Auth::user()->id;
return view('Frontend.specialists.dashboard.index');
}
...
}
But if in any case you need the id param, you can provide the value for it in redirect by doing
return redirect()->route('frontend.specialist.dashboard', ['id' => $id]);
I have a signup route. After it register on step1, it emails to the user to verify his account and have a link on his email. After clicking the link, it should redirect to signup/step2, and finished and he can access the job-seeker/home.
so the logic is after finished the registration, user cannot visit again to signup/step2 cause user already finished fill up the form.
and before fillup signup/step2, he can't access also the job-seeker/home. So it's vice versa.
basically my middleware was first: check if the user completed the step2 and added true on column is_completed in database. then on the second middleware is to visit only his route by his role, he can't access other routes from other role and redirect to his home based on his role.
But it throws me too many redirect and switching both side even I still didn't fill up the step2 yet. this is my gif below.
MyCode
Kernel.php
class Kernel extends HttpKernel
{
...
protected $routeMiddleware = [
...
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'isCompleted' => \App\Http\Middleware\IsCompleted::class,
];
Middleware/IsCompleted.php
class IsCompleted
{
public function handle($request, Closure $next)
{
if(auth()->user()->isCompleted == 1){
return $next($request);
}
// if 0, redirect to step2
return redirect()->route('register.step2');
}
Middleware/RedirectIfAuthenticated.php
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if ( Auth::user()->hasRole('job-seeker') ) {
return redirect()->route('job-seeker.home');
} else if(Auth::user()->hasRole('admin')) {
return redirect()->route('admin.home');
}
}
return $next($request);
Routes/Web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['verified', 'isCompleted']], function() {
Route::group(['prefix' => 'admin', 'name' => 'admin.'], function() {
Route::get('/home', function(){ return "test"; })->name('admin.home');
});
Route::group(['prefix' => 'job-seeker', 'name' => 'job-seeker.'], function() {
Route::get('/home', 'Jobseeker\HomeController#index')->name('job-seeker.home');
});
});
Auth::routes(['verify' => true, 'register' => false]);
Route::get('signup/{usertype}' , 'Auth\RegisterController#getStep1')->name('register.step1');
Route::post('signup/{usertype}' , 'Auth\RegisterController#postStep1');
Route::group(['middleware' => ['auth']], function() {
Route::get('signup/step2' , 'Auth\RegisterController#getStep2')->name('register.step2');
Route::post('signup/step2' , 'Auth\RegisterController#postStep2');
});
EDIT 1
I inspect the page and go to network tab, and this is the result.
your RedirectIfAuthenticated keeps redirecting all the time. It doesn't ever get to $next($request) for Authenticated User.
You need to have some logic like
if (route is seeker.home and user can visit seeker.home) {
return $next(request);
}
instead of
return redirect()->route('job-seeker.home');
I am experiencing this error when trying to navigate to "/admin". Other routes such as "/employee" are working fine.
Here are my current web routes
Auth::routes();
/* Voyager Routes */
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
...
});
/* Badge App Routes - All the dashboard routes for managers, employees and HRs are defined here */
Route::group(['middleware' => 'auth', 'prefix' => 'employee'], function () {
Route::get('/', 'frontend\DashboardController#index')->name('homepage');
Route::get('dashboard', 'frontend\DashboardController#index')->name('homepage');
...
});
Route::group(['middleware' => 'auth'], function () {
Route::resource('team-manager', 'frontend\TeamManagerController');
Route::resource('badges', 'backend\BadgeController');
Route::get('badges/award/{id?}', 'backend\BadgeController#award');
Route::post('store_award', 'backend\BadgeController#storeAward')->name('store_award');
});
/* User Redirector - Based on user role */
Route::group(['middleware' => ['redirector']], function () {
Route::get('/');
Route::get('login');
});
And here's my middleware redirector
public function handle($request, Closure $next){
if (!Auth::guest()) {
$user = User::find(Auth::id());
// TODO: fix static id below
return $user->role_id == 1 ? redirect('admin') : redirect('employee');
}
return redirect(route('voyager.login'));
}
Thank you in advance!
The problem is in your middleware:
return $user->role_id == 1 ? redirect('admin') : redirect('employee');
You have admin role, and you are also in /admin page. Then your middleware redirects you again and again to /admin.
It is better to check if the user is not in the /admin or /admin/* related routes, then redirect him to admin.
if($user->role_id == 1) {
//check if user is in /admin or /admin related routes.
return ($request->is('/admin') or $request->is('/admin/*')) ? $next($request) : redirect('admin');
} else {
redirect('/employee');
}
When I am making a API call to the http://localhost/lvl53/public/api/getSongs using Postman I get the following error.
FatalErrorException
Doctrine\Common\Proxy\AbstractProxyFactory::getProxyDefinition(): Failed opening required.
https://i.stack.imgur.com/TNEhO.png
Here are my routes web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::group(['middleware' => ['web','auth']], function () {
Route::get('/song', 'SongController#index')->name('song');
Route::get('/addSong', 'SongController#addSong')->name('addNewSong');
Route::post('/registerSong', 'SongController#create')->name('registerSong');
});
Route::get('/home', 'HomeController#index')->name('home');
Here is api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => ['web']], function () {
Route::get('/getSongs', 'SongController#getSongs')->name('getSongs');
});
But if I add the API route getSongs to the Route::Group in web.php and after logging in make the call, then I am able to retrieve data.
Here's my SongController's getSongs method
public function getSongs(EntityManagerInterface $em)
{
$songs = $em->getRepository(SongEntity::class)->findAll();
$songList = [];
\Log::info(["Songs",$songs]);
foreach ($songs as $song){
$currentSong["artist"] = $song->getArtist();
$currentSong["title"] = $song->getTitle();
$currentSong["url"] = $song->getUrl();
array_push($songList, $currentSong);
}
return $songList;
/*return view('song.songs', ['songs' => Song::all()]);*/
}
In here when making the api call \Log doesn't create a log. How to retrieve data using the API?
PS: When I looked into error msg they say I have do advance configurations on doctrine, it doesn't make sense. Any help is highly appreciated.
PPS: Do you think it has do something with attaching a authenticated user to SongEntity when creating the SongEntity?
Here's what happens when creating a SongEntity.
protected function create(Request $request, EntityManagerInterface $em)
{
$user = Auth::user();
//\Log::info($user);
$data = $request->input();
$this->validate($request, [
'title' => 'required|string|max:255',
'artist' => 'required|string|max:255',
'url' => 'required|string|url|unique:App\Entities\SongEntity',
]);
$song = new SongEntity(
$data['title'],
$data['artist'],
$data['url'],
$user
);
$em->persist($song);
$em->flush();
/* Song::create([
'title' => $data['title'],
'artist' => $data['artist'],
'url'=> $data['url']
]);*/
return redirect('song');
}
I am creating an application in Laravela and when I try to visit my url, for example: http://example.com it is returning this weird error? This only happens when I am not visiting /login?
InvalidArgumentException in UrlGenerator.php line 304:
Route [login] not defined.
Code:
use App\Http\Controllers\Frontend;
Route::group(['domain' => 'localhost', 'namespace' => 'Frontend'], function() {
Route::group(['middleware' => 'guest', 'namespace' => 'Guest'], function() {
Route::get('/', function() { return Redirect::to('/login'); });
Route::get('/login', 'LoginController#getView');
Route::post('/login', 'LoginController#onPost');
});
Route::group(['middleware' => 'auth', 'namespace' => 'User'], function() {
Route::get('/', function() { return Redirect::to('/home'); });
Route::get('/home', 'HomeController#getView');
Route::get('/logout', 'LogoutController#performLogout');
});
});
Route::group(['domain' => 'admin.localhost'], function() {
Route::get('/', function() {
return 'Housekeeping will be making an appearance soon!';
});
});
Here is my LoginController:
<?php
namespace App\Http\Controllers\Frontend\Guest;
use Auth;
use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Redirect;
use Illuminate\Http\Request;
use App\Database\Frontend\User\Player;
use App\Database\Frontend\WebsiteLogin;
class LoginController extends Controller
{
public function getView()
{
return view('frontend.login');
}
public function onPost(Request $request)
{
$validator = Validator::make($request->all(), [
'mail' => 'required|email|exists:users',
'password' => 'required'
]);
if ( $validator->fails()) {
return Redirect::to('/login')->withErrors($validator->messages());
}
else {
if (!Auth::attempt(['mail' => $request->input('mail'), 'password' => $request->input('password')])) {
$this->addNewWebsiteLogin($request, Player::where('mail', $request->input('mail'))->pluck('id')->first(), "0");
return Redirect::to('/login')->withMessage('Email and password do not match')->withColor('danger');
}
else {
$this->addNewWebsiteLogin($request, Auth::user()->id, "1");
$user = Auth::user();
$user->last_online = time();
$user->save();
/*if (config('frontend.government_only') && (Auth::Guest() || Auth::user()->roleplay->government_id == 0)) {
Auth::logout();
return Redirect::to('/login')->withMessage(config('frontend.site_name') . ' is only open to government individuals at this moment, too bad.')->withColor('danger');
}*/
return Redirect::to('/home')->withMessage('Welcome back!');
}
}
}
private function addNewWebsiteLogin(Request $request, $userId, $status) {
$websiteLogin = new WebsiteLogin;
$websiteLogin->user_id = $userId;
$websiteLogin->request_ip = $request->ip();
$websiteLogin->request_system = 'TODO';
$websiteLogin->request_browser = 'TODO';
$websiteLogin->login_status = $status;
$websiteLogin->save();
}
}
Looks like you're using route('login') to create a link to the login page or in form.
If you're using it in a link, just name get() route:
Route::get('login', ['as' => 'login', 'uses' => 'LoginController#getView']);
If you're using the route() helper in a form, do this for the post() route.
You can use the artisan comp php artisan make:auth to scaffold the authentication pages needed.
You can find the documentation for that here, https://laravel.com/docs/5.4/authentication
if you have, login route like this:
Route::post('login', ['middleware' => 'guest', 'uses' => 'UserController#postLogin',]);
just need to add :
->name('login');
at the end of your route s.th like this.
your result s.th like this:
Route::post('login', ['middleware' => 'guest', 'uses' => 'UserController#postLogin',])->name('login');