How To Change Login & Register View in Laravel - laravel

I'm new to Laravel, so here I want to make a view for login and register, and then I change the default view login and register into my own view, I changed it in the route and then it work, and then I try to run this code: php artisan ui:auth and then my login view before, it changes to the default view of Laravel. How to change it again into my login and view design ? Thank you.
This is my route web.php:
<?php
/*
|--------------------------------------------------------------------------
| 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::get('/', function () {
return view('pages/home');
});
Route::get('/register','Auth\AuthController#register');
Route::post('/register','Auth\AuthController#postRegister')->name('register');
Route::get('/login','AuthController#login');
Route::post('/login','AuthController#postLogin')->name('login');
and this is my AuthController
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class AuthController extends Controller
{
public function register()
{
return view('login_register/register');
}
public function postRegister(Request $request )
{
User::create([
'name'=> $request->nama,
'email'=> $request->email,
'password'=> bcrypt($request->password)
]);
return redirect('/login');
}
public function login()
{
return view('login_register/login');
}
public function postLogin(Request $request)
{
if(!\Auth::attempt(['email' => $request->email, 'password' => $request->password ])){
return redirect()->back();
}
return redirect('/galangdana/list');
}
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
/**
* Obtain the user information from provider. Check if the user already exists in our
* database by looking up their provider_id in the database.
* If the user exists, log them in. Otherwise, create a new user then log them in. After that
* redirect them to the authenticated users homepage.
*
* #return Response
*/
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect('/');
}
/**
* If a user has registered before using social auth, return the user
* else, create a new user object.
* #param $user Socialite user object
* #param $provider Social auth provider
* #return User
*/
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
else{
$data = User::create([
'name' => $user->name,
'email' => !empty($user->email)? $user->email : '' ,
'provider' => $provider,
'provider_id' => $user->id
]);
return $data;
}
}
}
?>

You can override the showLoginForm() method, in you LoginController.php:
public function showLoginForm()
{
return view('my.view');
}
It overrides the function showLoginForm defined in the trait Illuminate\Foundation\Auth\AuthenticatesUsers.
For registration, you showRegistrationForm method, defined in Illuminate\Foundation\Auth\RegistersUsers trait:
public function showRegistrationForm()
{
return view('my.register.view');
}
Hope it helps.

solved, that becasue i put Auth::routes() so that make multiple login, thank you for the answer 🙏

Related

How to set user and admin on different dashboard url in laravel

I'm working on a project where user and admin are two different login. I want to redirect user and admin to their respective dashboard pages.
I'm not getting how to do this. In database, I created roles column (1 for admin, 2 for user).
I'm not getting how to set send to a different dashboard.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator,Redirect,Response;
Use App\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Session;
use Socialite;
class AuthController extends Controller
{
public function index()
{
return view('login');
}
public function registration()
{
return view('registration');
}
public function postLogin(Request $request)
{
request()->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
// return redirect($this->redirectPath());
}
return Redirect::to("login")->withSuccess('Oppes! You have entered invalid credentials');
}
}
Currently on successful login going only same dashboard. I want to change that and send redirection according to roles.
I have created middleware also, but not getting what exact need to do.
<?php
namespace App\Http\Middleware;
use Closure;
Use App\User;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
$auth = Auth::user()->roles()->first();
switch ($auth->role) {
case 'admin':
return redirect()->route('admin');
break;
case 'user':
return redirect()->route('user');
break;
default:
return redirect()->route('login');
break;
}
}
return $next($request);
}
}
and routing will be following
Route::get('login', 'AuthController#index');
Route::post('post-login', 'AuthController#postLogin');
First of all, you don't need to create a middleware for redirecting users based on their role.
Just check the role of user after successful login attempt and do your redirect.
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
// Set redirect route/path based on user role.
$to = $request->user()->role->name === 'admin' ? 'admin' : 'user';
// Redirect user to a named route.
return redirect()->route($to); // or return redirect($to);
}
return Redirect::to('login')->withSuccess('Oops! You have entered invalid credentials.');
}
You can Manage different different dashboards for User and Admin URLs Easily using Gates method also in Laravel.
refer and Try to understand this Example,

Authentication redirect route

can you help me how to create if isadmin is true it will be redirected to admin page, else home page.
AuthController
public function postLogin(Request $request){
if(!auth()->attempt(['email' => $request->email, 'password' => $request->password])){
return redirect()->back();
}
return redirect()->route('home');
}
the main reason's maybe because this
return redirect()->route('home');
when tried change to ('admin') it successfully redirecting.
when i tried to add
protected function authenticated(\Illuminate\Http\Request $request, $user)
{
if( $user->isadmin){
return redirect('admin');
}
return redirect('home');
}
it didnt works too
My approach to this situation is using middleware as #sssurii told you
I have a roles table which states normal users and admin user, and additionally I have a middleware such the following:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Auth::user();
if(!$user->role->title==='Admin'){
return route('user');
}
return $next($request);
}
}
Then in kernel class, I've added that middleware in routes
protected $routeMiddleware = [
....
'isAdmin' => \App\Http\Middleware\AdminMiddleware::class
];
Now you need to protect your admin routes, it is solver by
Route::group(['middleware' => ['auth', 'isAdmin'],
'prefix' => 'admin', 'as' => 'admin.'], function () {
Route::get('/home', 'Admin\HomeController#index')->name('dashboard');
.....
}
Here you have a way to filter requests to admin routes, and let get in only users that belongs to group/role Admin.
After that if you want an automatic redirect at login, you should modify redirectPath function in Auth controller (usually at app/http/controllers/auth/AuthController.php)
public function redirectPath()
{
if (\Auth::user()->role->title === 'Admin') {
return redirect()->route('admin.dashboard');
}
return redirect()->route('user.dashboard');
}
I suggest creating a middleware and using it to protect the route
Example, you can create an Admin middleware
php artisan make:middleware Admin
In App\Http\Middleware\Admin.php
use Auth;
use Session;
use Closure;
public function handle($request, Closure $next)
{
// Check if user has permission to access route
if(!Auth::user()->admin) {
Session::flash('info', 'You do not have permission to perform this operation!');
return redirect()->back();
}
return $next($request);
}
Then in the protected route(assuming only your admin can view all posts in this route),
Route::post('admin/post/index', 'PostController#index')->middleware('auth');
Or in the controller
public function __construct()
{
$this->middleware('auth');
}
Use except to exclude routes or only to include methods.
In the kernel.php
protected $routeMiddleware = [
...
'admin' => \App\Http\Middleware\Admin::class
];

Default controller in Route::group for routing purposes?

I want to show some user data by id. Simple.
user/{id} -> get data from a Controller's method.
I have this:
Route::group(['prefix' => 'user/{id}', 'where' => ['id' => '[0-9]+']], function() {
Route::get('delete', 'UserController#delete')->name('admin.access.user.delete-permanently');
Route::get('restore', 'UserController#restore')->name('admin.access.user.restore');
Route::get('mark/{status}', 'UserController#mark')->name('admin.access.user.mark')->where(['status' => '[0,1]']);
Route::get('password/change', 'UserController#changePassword')->name('admin.access.user.change-password');
Route::post('password/change', 'UserController#updatePassword')->name('admin.access.user.change-password');
});
How can I access a method as a default for user/{id}?
You can do this in your controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//Fetch and send the user to the "profile" blade file in the folder "resources/views/user"
return view('user.profile', ['user' => User::findOrFail($id)]);
}
public function changePassword($id)
{
$user = User::findOrFail($id);
return $user->update(
'password' => bcrypt(123456)
);
}
}

Method [validate] does not exist. - Laravel 5.5

I'm trying "laravel-modules" and "Laravel-permission package". But when run post, it has issue 'Method [validate] does not exist.'. i have added 'use Validator;' but no thing change. In some topics, i remove "use Illuminate\Routing\Controller;" in PermissionController, but it have error
Controller
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
My PermissionController
namespace Modules\User\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Auth;
//Importing laravel-permission models
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Session;
class PermissionController extends Controller
{
// use Validator;
public function __construct() {
$this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources
}
/**
* Display a listing of the resource.
* #return Response
*/
public function index()
{
$permissions = Permission::all(); //Get all permissions
return view('user::permissions/index')->with('permissions', $permissions);
// return view('user::index');
}
/**
* Show the form for creating a new resource.
* #return Response
*/
public function create()
{
$roles = Role::get(); //Get all roles
return view('user::permissions/create')->with('roles', $roles);
}
/**
* Store a newly created resource in storage.
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name'=>'required|max:40',
]);
$name = $request['name'];
$permission = new Permission();
$permission->name = $name;
$roles = $request['roles'];
$permission->save();
if (!empty($request['roles'])) { //If one or more role is selected
foreach ($roles as $role) {
$r = Role::where('id', '=', $role)->firstOrFail(); //Match input role to db record
$permission = Permission::where('name', '=', $name)->first(); //Match input //permission to db record
$r->givePermissionTo($permission);
}
}
return redirect()->route('permissions.index')
->with('flash_message',
'Permission'. $permission->name.' added!');
}
}
Route
Route::group(['middleware' => 'web', 'prefix' => 'permissions', 'namespace' => 'Modules\User\Http\Controllers'], function()
{
Route::get('/', 'PermissionController#index');
Route::get('/create', 'PermissionController#create');
Route::post('/', 'PermissionController#store');
Route::delete('/', ["as" => "permissions.destroy", "uses" => "PermissionController#destroy"]);
});
Add back in use Validator in your PermissionController. Add this right after use Auth;. You have currently added this in the wrong place.
Then change your $this->validate(...) code to:
// validate the input
$validation = Validator::make( $request->all(), [
'name'=>'required|max:40',
]);
// redirect on validation error
if ( $validation->fails() ) {
// change below as required
return \Redirect::back()->withInput()->withErrors( $validation->messages() );
}
I was trying
$this->validate($request, [
'password' => 'required|confirmed|min:6',
]);
But in Laravel 5.7 following code did the trick for me
$request->validate([
'password' => 'required|confirmed|min:6',
]);

'middleware' => 'auth'. I cant access my dashboard

It was successfuly protected, it will redirect back to the login page when the user try to type /dasboard to the URL. but the problem is, I cant access my dashboard even I input the correct email and password..
this my userController.php file
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class userController extends Controller
{
public function getDashBoard()
{
return view('dashboard');
}
public function login(Request $request)
{
$this->validate($request, [
'email'=> 'required',
'password'=> 'required'
]);
if(Auth::attempt(['email'=> $request['email'], 'password'=> $request['password']])){
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
this my routes.php file
Route::group(['middleware' => ['web']], function () {
Route::get('/', function() {
return view('login');
})->name('home');
Route::get('/dashboard', [
'uses'=> 'userController#getDashBoard',
'as'=> 'dashboard'
'middleware' => 'auth'
]);
});
and this my Authenticate.php file
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('home');
}
}
return $next($request);
}
}
I need help. I'am new in this laravel 5.2 framework. better if you edit my code so that I could understand and know my mistake..
Thank you for understanding. Slow learner here..
According to the code provided there doesn't seem to be a getDashBoard method within your UserController. Your 'dashboard' route is pointing to a method that doesn't exist.
I dont know why, but when I turn off the machine to take a sleep. And then turn on the machine again. When I run my application it was suddenly fix.. hmmmm...

Resources