Bad routes for admin in Laravel - php

I am a newbie in Laravel and wanna create Admin Login and Registration. I have user registration and it works properly.
My web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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::view('/', 'index');
Route::name('user.')->group(function () {
Route::view('/private', 'private')->middleware('auth')->name('private');
Route::get('/login', function() {
if (Auth::check()) {
return redirect(route('user.private'));
}
return view('login');
})->name('login');
Route::post('/login', [\App\Http\Controllers\LoginController::class, 'login']);
Route::get('/logout', function () {
Auth::logout();
return redirect('/');
})->name('logout');
Route::get('/registration', function() {
if (Auth::check()) {
return redirect(route('user.private'));
}
return view('registration');
})->name('registration');
Route::post('/registration', [\App\Http\Controllers\RegisterController::class, 'save']);
});
Route::name('admin.')->group(function () {
Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('adminPrivate');
// dd(Route::view('/adminPrivate', 'adminPrivate')->middleware('auth')->name('private'));
Route::get('/adminLogin', function() {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
return view('adminLogin');
})->name('login');
Route::post('/adminLogin', [\App\Http\Controllers\LoginAdminController::class, 'login']);
Route::get('/adminLogout', function () {
Auth::guard('admin')->logout();
return redirect('/');
})->name('logout');
Route::get('/adminRegistration', function() {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
return view('adminRegistration');
})->name('registration');
Route::post('/adminRegistration', [\App\Http\Controllers\RegisterAdminController::class, 'save']);
});
My RegisterAdminController.php
<?php
namespace App\Http\Controllers;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RegisterAdminController extends Controller
{
public function save(Request $request) {
if (Auth::guard('admin')->check()) {
return redirect(route('admin.adminPrivate'));
}
$validateFields = $request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Admin::where('username', $validateFields['username'])->exists()) {
return redirect(route('admin.registration'))->withErrors([
'username' => 'Username already registered!'
]);
}
$admin = Admin::create($validateFields);
if ($admin) {
Auth::guard('admin')->login($admin);
return redirect(route('admin.adminPrivate'));
}
return redirect(route('admin.login'))->withErrors([
'formError' => 'Cannot save admin!'
]);
}
}
My LoginAdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
class LoginAdminController extends Controller
{
public function login(Request $request) {
if (Auth::guard('admin')->check()) {
return Redirect::to(route('admin.adminPrivate'));
}
$formFields = $request->only(['username', 'password']);
if (Auth::guard('admin')->attempt($formFields)) {
return Redirect::to(route('admin.adminPrivate'));
}
return redirect(route('admin.login'))->withErrors([
'username' => 'Can not authorize'
]);
}
}
I don't understand how I can solve this problem. Need a help. I tried modify all names of my Routes, but this didn't help.

Related

Problems getting Auth:: user()

I'm new to Laravel. I want to get an authorized user using the Auth::user () facade, in order to extract its ID, in the logout() method this is obtained and the authorized user is returned as an array with its data, but in the store() method Auth:: user () returns null. Tell me, please, what is the problem?
AuthController (here is logout()):
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserLoginRequest;
use Egulias\EmailValidator\Exception\AtextAfterCFWS;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;
class AuthController extends Controller
{
public function store(UserCreateRequest $request){
$user = new User();
$user->login = $request->get('login');
$user->password = Hash::make($request->get('password'));
$user->email = $request->get('email');
$user->number_phone = $request->get('number_phone');
$user->assignRole('user');
if (!$user->save()) {
return response()->json(['message'=>'Регистрация не удалась']);
}
return response()->json(['message'=>$user->jsonSerialize()]);
}
public function login(UserLoginRequest $request){
$user = User::query()->where('login', $request->get('login'))->first();
if (!$user || !Hash::check($request->get('password'), $user->password)) {
return response()->json(['message'=>'Попытка входа не удалась'], 400);
}
$token = $user->createToken('api_token')->plainTextToken;
$user->api_token = $token;
$user->save();
$user = Auth::login($user);
return response()->json(['message'=>Auth::user()->api_token], 200);
}
public function logout(Request $request) {
dd(Auth::user());
$request->user()->currentAccessToken()->delete();
return response()->json(['message' => 'Вы вышли из системы'], 200);
}
AuthController (here is store()):
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ApplicationCreateRequest;
use Illuminate\Http\Request;
use App\Models\Application;
use App\Models\Status;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class ApplicationController extends Controller
{
public function showById($id) {
return response()->json(Application::find($id), 200);
}
public function show() {
return response()->json(Application::all(), 200);
}
public function store(ApplicationCreateRequest $request){
dd(Auth::user());
//$application = new Application();
//dd(Auth::user()->api_token);
//$application->user_id = Auth::id();
//$application->status_id = 1;
//$application->description = $request->get('description');
//
//if (!$application->save()) {
// return response()->json(['message'=>'Заявка не отправлена'], 500);
//}
//
//return response()->json(['message'=>$application->jsonSerialize()]);
}
public function delete(Application $application) {
if ($application->delete()) {
return response()->json('Заявка удалёна', 200);
}
return response()->json(['message' => 'Заявка не удалёна'], 500);
}
// public function updateStatus(Application $application)
// {
// if ($application->status_id)
// }
}
api.php:
<?php
use App\Http\Controllers\ApplicationController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ReviewController;
use App\Http\Controllers\AdminController;
use App\Http\Requests\UserLoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => ['role:admin']], function () {
});
Route::post('login', [AuthController::class, 'login']);
Route::post('authStore', [AuthController::class, 'store']);
Route::get('authLogout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
Route::get('application/{id}', [ApplicationController::class, 'showById']);
Route::get('application', [ApplicationController::class, 'show']);
Route::post('applicationStore', [ApplicationController::class, 'store'])->middleware('auth:sanctum');
Route::post('applicationDelete/{application}', [ApplicationController::class, 'delete'])->middleware('auth:sanctum');
//Route::post('userDelete/{user}', [AdminController::class, 'delete']);
Route::post('userStore', [AdminController::class, 'store']);
Route::get('user', [AdminController::class, 'show']);
Route::get('user/{id}', [AdminController::class, 'showById']);
Route::post('userDelete/{user}', [AdminController::class, 'delete'])->middleware('auth:sanctum');
Route::get('review', [ReviewController::class, 'showReview']);
Route::get('review/{id}', [ReviewController::class, 'showReviewById']);
Route::post('reviewStore', [ReviewController::class, 'store'])->middleware('auth:sanctum');
Route::post('reviewUpdate/{id}', [ReviewController::class, 'updateReview'])->middleware('auth:sanctum');
Route::post('reviewRatingUpdate/{id}', [ReviewController::class, 'updateReviewRating'])->middleware('auth:sanctum');
Route::get('reviewRating', [ReviewController::class, 'showReviewRating'])->middleware('auth:sanctum');
Route::get('reviewRating/{id}', [ReviewController::class, 'showReviewRatingById']);
Route::get('authUser', [AuthController::class, 'user']);
Define middleware in the constructer of your controller and it will do the trick here
public function __construct()
{
$this->middleware('auth:api');
}
Or moved the route into Route::middleware it will work
Route::middleware('auth:api')->group( function () {
Route::post('authStore', [AuthController::class, 'store']);
});
Use
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
at the start
register method
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
'mobile' => 'required|min:10',
]);
if ($validator->fails()) {
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
[
'password' => bcrypt($request->password),
]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user
], 201);
}

Route [login] not defined.laraval 6.0

I make an admin panel using laravel 6.0 I want to make a guard to my admin panel for when trying access without login and then should redirect back to the login page. I tried these code but I got errors. route defined so I can't figure out the problem.
this is the error
Handler.php
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [login] not defined.
<?php
namespace App\Exceptions;
use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
protected $dontReport = [
];
protected $dontFlash = [
'password',
'password_confirmation',
];
public function report(Exception $exception)
{
parent::report($exception);
}
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
public function unauthenticated($request, AuthenticationException $exception)
{
$guard = array_get($exception->guards(), 0);
switch ($guard) {
case 'admin':
return redirect()->guest(route('login'));
break;
default:
return redirect('/user/login');
break;
}
}
}
web.php
<?php
Route::prefix('admin')->group(function() {
Auth::routes();
Route::middleware('auth:admin')->group(function() {
Route::get('/', 'DashboardController#index');
Route::resource('/manageSISAccount', 'SISAccountController');
Route::get('/confirm/{id}','SISAccountController#confirm')->name('SIS.confirm');
Route::get('/pendig/{id}','SISAccountController#Pending')->name('SIS.Pending');
Route::get('/shpw/{id}','SISAccountController#show')->name('SIS.show');
Route::get('/logout','AdminUserController#logout');
});
Route::get('/login','AdminUserController#index');
Route::post('/login', 'AdminUserController#store');
});
AdminUserController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminUserController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
public function index(){
return view('admin.adminlogin');
}
public function store(Request $request) {
// Validate the user
$request->validate([
'email' => 'required|email',
'password' => 'required'
]);
// Log the user In
$credentials = $request->only('email','password');
if (! Auth::guard('admin')->attempt($credentials)) {
return back()->withErrors([
'message' => 'Wrong credentials please try again'
]);
}
// Session message
session()->flash('msg','You have been logged in');
return redirect('/admin');
}
public function logout() {
auth()->guard('admin')->logout();
session()->flash('msg','You have been logged out');
return redirect('/admin/login');
}
}
You did not name your login route.
Change:
Route::get('/login','AdminUserController#index');
To:
Route::get('/login','AdminUserController#index')->name('login');
For more information about naming routes: https://laravel.com/docs/6.x/routing#named-routes
Route::get('/login',['uses'=>'AdminUserController#index#index','as'=>'login']);

In a Laravel 5.4 app, when I try to login, it redirects to same login page

Web.php
Route::get('/' , ['as' => '/' , 'uses'=> 'loginController#getlogin']);
Route::post('/login', ['as' => 'login', 'uses'=> 'loginController#postlogin']);
Route::group(['middleware' =>['authen']],function (){
Route::get('/logout' ,['as'=>'logout', 'uses'=> 'loginController#getLogout']);
Route::get('/dashboard',['as'=>'dashboard', 'uses'=> 'dashboardController#dashboard']);
});
dashboardController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class dashboardController extends Controller
{
public function __construct()
{
$this->middleware('web');
}
public function dashboard()
{
return view('layouts.master');
}
}
Authen.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authen
{
public function handle($request, Closure $next ,$guard ='web')
{
if (!Auth::guard($guard)->check())
{
return redirect()->route('/');
}
return $next($request);
}
}
loginController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
class loginController extends Controller
{
use AuthenticatesUsers;
protected $username = 'username';
protected $redirectTo = '/dashboard';
protected $guard = 'web';
public function getLogin()
{
if (Auth::guard('web')->check())
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postlogin(Request $request)
{
$auth = Auth::guard('web')->attempt(['username'=>$request->username,'password'=>$request->password,'active'=>1]);
if ($auth)
{
return redirect()->route('dashboard');
}
return redirect()->route('/');
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
}
When I try to login it redirects to the same page i.e login page, I tried to solve this problem but I can't. I want to redirect dashboard through login page, but it is not happen. There is no error shown and I can't go on dashboard page too.
Try this way in postlogin function to check user authentication.
$auth = Auth::attempt(['username'=>$request->username,'password'=>$request->password,'active'=>1]);
if($auth){
//do something...
}

Don't working authentication in laravel 5.2

Don't working authentication. I create authentication manually.
My AdminController:
class AdminController extends Controller
{
public function signin() {
return view('admin.signin');
}
public function index(Request $request) {
dd(Auth::check());
if (Auth::check())
return view('admin.index.index', ['login' => Auth::user()->name]);
else
return redirect()->action('AdminController#signin');
}
public function login() {
$data = Input::all();
if (Auth::attempt(['name' => $data['login'], 'password' => $data['password']])) {
return redirect()->intended('/admin');
} else {
return redirect()->intended('/admin/signin');
}
}
public function logout() {
if (Auth::logout() ) {
return Redirect::to('/admin');
}
}
}
My routes.php file:
//GET
Route::get('/', 'IndexController#index');
Route::get('/admin/signin', 'AdminController#signin');
Route::get('/admin', 'AdminController#index');
Route::get('/admin/logout', 'AdminController#logout');
//POST
Route::post('/admin/auth', 'AdminController#login');
dd(Auth::check()); returned false
What I doing wrong?
In Laravel 5.2 you need to define routes using web middleware to make sessions work, so your routes.php file should look like this:
Route::group(['middleware' => ['web']], function () {
//GET
Route::get('/', 'IndexController#index');
Route::get('/admin/signin', 'AdminController#signin');
Route::get('/admin', 'AdminController#index');
Route::get('/admin/logout', 'AdminController#logout');
//POST
Route::post('/admin/auth', 'AdminController#login');
});

Routing confusion on two admin in laravel 4

I have following routes:
// For user
Route::controller('/', 'LoginController');
//For admin
Route::group(array('prefix' => 'admin'), function() {
Route::get('/', 'admin\LoginController#index');
Route::get('/dashboard', 'admin\LoginController#show');
Route::get('/Logout','admin\LoginController#logout');
Route::resource('/setting','admin\SettingController');
});
I have user panel without prefix.
In logincontroller contain authorization codes.
I have found 'Controller method not found.' error when i open admin.but when i comment to user route then admin is working fine but user panel found same error.please help sir..thanks
Yes Here is LoginController of user
<?php
class LoginController extends BaseController {
public function getIndex()
{
if(Auth::check())
{
return Redirect::to('/user/home');
}
return View::make('login.index');
}
public function postIndex()
{
$username = Input::get('username');
$password = Input::get('password');
if (Auth::attempt(['username' => $username, 'password' => $password]))
{
return Redirect::intended('/user/home');
}
return Redirect::back()
->withInput()
->withErrors('Sorry,Username or password is incorrect');
}
public function getLogin()
{
return Redirect::to('/');
}
public function getLogout()
{
Auth::logout();
return Redirect::to('/');
}
}
Admin Login Controller
<?php
namespace admin;
class LoginController extends \BaseController {
public function showLogin() {
return \View::make('admin.login');
}
public function index()
{
return \View::make('admin.index');
}
public function store()
{
$username = \Input::get('username');
$password = md5(\Input::get('password'));
if ($mm=\DB::select('select * from admin where uname = ? and password = ?', array($username, $password)))
{
\Session::put('admin', $mm);
return \Redirect::intended('/admin/dashboard');
}
else
{
\Session::flush('admin');
return \Redirect::back()
->withInput()
->withErrors('Sorry,Unauthorized admin please try again');
}
}
public function postIndex()
{
echo 'Demo of post index';exit;
}
public function show()
{
$tt=\Session::get('admin');
return \View::make('admin.dashboard');
}
public function Logout()
{
\Session::flush('admin');
return \Redirect::to('/admin');
}
}
The problem is that Route::controller('/') is catching all requests that only have one segment. that means /admin as well. It then tries to find a getAdmin() method in the user LoginController which obviously doesn't exist.
You basically have two options here.
1. Change the route order
Routes are searched in the order you register them. If you place the admin group before the other route everything will work as expected:
Route::group(array('prefix' => 'admin'), function() {
Route::get('/', 'admin\LoginController#index');
Route::get('/dashboard', 'admin\LoginController#show');
Route::get('/Logout','admin\LoginController#logout');
Route::resource('/setting','admin\SettingController');
});
Route::controller('/', 'LoginController');
2. Make explicit routes
Instead of using Route::controller('/') you could specify each route:
Route::get('/', 'LoginController#getIndex');
Route::get('login', 'LoginController#getLogin');
// etc...
Route::group(array('prefix' => 'admin'), function() {
Route::get('/', 'admin\LoginController#index');
Route::get('/dashboard', 'admin\LoginController#show');
Route::get('/Logout','admin\LoginController#logout');
Route::resource('/setting','admin\SettingController');
});

Categories