Laravel Fortify Logout Redirect - laravel

Hello guys is there any ways to redirect the logout function of Fortify?
<div class="nav-link" id="nav-bar-logoutbutton">
<form method="POST" action="{{ route('logout') }}">
#csrf
<button class="btn btn-secondary btn-sm" type="submit">Logout</button>
</form>
</div>
this is my blade logout

You can do the following:
Create a new LogoutResponse class and implement your redirect logic into the toResponse method:
"app/Http/Responses/LogoutResponse.php"
<?php
namespace App\Http\Responses;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;
use Symfony\Component\HttpFoundation\Response;
class LogoutResponse implements LogoutResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* #param Request $request
*
* #return Response
*/
public function toResponse($request)
{
return $request->wantsJson()
? new JsonResponse('', 204)
: redirect('www.example.com');
}
}
Now you can bind the new response into the service container in the boot method of your FortifyServiceProvider:
"app/Providers/FortifyServiceProvider.php"
public function boot()
{
$this->app->singleton(
\Laravel\Fortify\Contracts\LogoutResponse::class,
\App\Http\Responses\LogoutResponse::class
);
}

In your config/fortify.php, add:
'redirects' => [
'logout' => 'login',
],

Just create a new post request in your routes/web.php
Route::post('logout', [ClientController::class, 'logout'])->name('logout');
Now in your controller, create a function to handle the request, make sure to include the Auth class at the top.
use Auth;
/* Process the logout request */
public function logout(Request $request) {
Auth::logout();
return redirect('/login')->with(['msg_body' => 'You signed out!']);
}
Instead of /login, you can redirect to anywhere.

Related

Laravel login features

I'm working on Laravel task and struggling to add a login feature. Register and validation features seem work well, but can't login even if i put correct user_name and pass_word. also old helper function is not working as well.
i am a very beginner of Laravel and I know my code is messy and not coherent. But need to get this task done. appreciate if you help me solve this!
So here are files of my task. when i tried to login it always goes to this page.
<?php
use App\Http\Controllers\RegisterController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| 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('users/list', 'App\Http\Controllers\UserController#getUser');
Route::get('register', [RegisterController::class, 'create'])->middleware('guest');
Route::post('register', [UserController::class, 'register'])->middleware('guest');
Route::get('login', [UserController::class, 'loginView']);
Route::post('login', [UserController::class, 'login']);
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserLoginRequest;
use App\Http\Requests\UserRegisterRequest;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
private $userService;
public function __construct(
UserService $userService
) {
$this->userService = $userService;
}
public function getUser() {
$users = User::all();
return view('users/list')
->with('users', $users);
}
public function register(UserRegisterRequest $request)
{
$this->userService->registerUser($request->user_name, $request->pass_word);
return redirect('users/list');
}
public function loginView()
{
return view('users/loginView');
}
public function login(Request $request)
{
$validatedData = $request->validate([
'user_name' => ['required'],
'pass_word' => ['required'],
]);
if (Auth::attempt($validatedData)) {
$request->session()->regenerate();
return redirect('users/list');
}
return back()->withErrors([
'user_name' => 'wrong username'
]);
}
}
<main>
<h1>Login!</h1>
<form action="login" method="POST">
#csrf
<div>
<label for="user_name">
User_name
<input type="text" name="user_name" id="user_name" value="{{ old('user_name') }}" >
</label>
#error('user_name')
<div class="error">{{ $message }}</div>
#enderror
</div>
<div>
<label for="pass_word">
Password
<input type="password" name="pass_word" id="pass_word" value="{{ old('pass_word') }}">
</label>
#error('pass_word')
<div class="error">{{ $message }}</div>
#enderror
</div>
<div>
<button type="submit">
Submit
</button>
</div>
</form>
</main>
<?php
namespace App\Services;
use Illuminate\Database\Eloquent\Collection;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class UserService
{
/**
*
*
* #param string $name
* #param string $email
* #param string $pass_word
* #return void
*/
public function registerUser($user_name, $pass_word) : void
{
$user = new User();
$user->user_name = $user_name;
$user->pass_word = Hash::make($pass_word);
$user->save();
}
}
enter image description here
First, if you want to redirect using back() helper to another controller method, you should put ->withInput or ->onlyInput('user_name').
back()->withErrors([
'user_name' => 'wrong username'
])->onlyInput('user_name');
or
back()
->withErrors([
'user_name' => 'wrong username'
])->withInput();
You may dump the errors on the view because probably it comes from the password error may be?

Permission issue in Laravel

I am facing problem regarding permission
Argument 1 passed to App\Providers\AuthServiceProvider::App\Providers{closure}() must be an instance of App\Providers\User, instance of App\User given, called in C:\xampp\htdocs\Tweety\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 473 (View: C:\xampp\htdocs\Tweety\resources\views\tweet.blade.php)
I am just working to show delete button only on those tweets made by the authenticated users
my controller
public function destroy(Tweet $tweet)
{
$tweet->delete();
Session::flash('success');
return redirect()->route('tweets.index')->with(['message' => 'Tweet Deleted']);
}
my user model
public function tweets()
{
return $this->hasMany(Tweet::class)->latest();
}
my blade
#can('delete',$tweet)
<form action="{{ route('tweets.destroy',$tweet->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
#endcan
AuthServiceProvider
public function boot()
{
$this->registerPolicies();
Gate::define('delete', function (User $user , Tweet $tweet){
return $tweet->user->is($user);
});
}
Any help will be appreciated
It looks like a namespace issue and didn't import User model's namespace correctly.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\User; // looks like you're missing this line.
use App\Tweet;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('delete', function (User $user , Tweet $tweet){
return $tweet->user->is($user);
});
}
}
You would need to change:
#can('delete', $tweet)
to:
#can('delete')

Laravel protected $loginView load the default login view

I am trying to login for different types of users
but I have an error starting the login view for a certain type of user
laravel default login view loads and not the one i created and assigned to protected $loginView
I cannot understand what is happening, what is the error that occurs?
Web.php:
Route::group(['middleware'=>'web'], function (){
Route::get('/', function () {
return view('welcome');
});
Route::get('admins/login','adminController#showLoginForm');
Route::get('admins/login','adminController#login');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
});
adminController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class adminController extends Controller
{
use AuthenticatesUsers;
protected $loginView = 'admins.login';
}
admins >login.blade.php:
<form method ="POST" action="">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
<label for="pass">password:</label>
<input type="text" name="pass" id="pass">
<button>login</button>
</form>
As far as I am aware, there is no $loginView property that Laravel utilizes to determine which view should be used for the login page, so why do you believe that it should work?
Here is the showLoginForm method:
public function showLoginForm()
{
return view('auth.login');
}
So what I would suggest you do is the following, remove the $loginView property and overwrite the showLoginForm method:
class adminController extends Controller
{
use AuthenticatesUsers;
public function showLoginForm()
{
return view('admins.login');
}
}
PS:
Why do you have the route admins/login with the method get twice?
Route::get('admins/login','adminController#showLoginForm');
Route::get('admins/login','adminController#login');
You probably meant to use post for the second one.

Laravel 5.4 set locale in session

Update.
I would like to know how to set locale in session.
my language picker isnt' input type, but just text. here is blade fragment - this is language picker:
<div class = "col-lg-5 col-md-5" id = "lang">
<ul id = "lang_menu">
<li class = "language active">Latviešu</a></li>
<li class = "language">Pусский</a></li>
<li class = "language">English</a></li>
</ul>
</div>
Here are routes:
Route::get('/', 'PagesController#index');
Route::get('/mafia', 'PagesController#mafia');
Route::get('/games', 'PagesController#games');
Route::get('/discounts', 'PagesController#discounts');
Route::get('/tournaments', 'PagesController#tournaments');
Route::get('/gallery', 'PagesController#gallery');
Route::get('/aboutus', 'PagesController#aboutus');
also i have transladet files who works fine when i changing locale in config
<<----------UPDATED----------------->>
Now i got so far but still its not working. I made this code from one tutorial where all works. I did the same and its not working.
Here is lang choosing Blade :
<ul id = "lang_menu">
<li class = "language active">Latviešu</li>
<li class = "language">Pусский</li>
<li class = "language">English</li>
</ul>
Here is routes:
Route::get('locale/{locale?}', array('as'=>'set-locale', 'uses'=>'LanguageController#setLocale'));
Here is my LanguageController:
use Illuminate\Http\Request;
use Session;
use URL;
class LanguageController extends Controller
{
public function setLocale($locale='en'){
if (!in_array($locale, ['en', 'ru', 'lv'])){
$locale = 'en';
}
Session::put('locale', $locale);
return redirect(url(URL::previous()));
}
}
And here is middleware "Locale":
use Closure;
use Session;
use Config;
use App;
class Locale
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$locale=Session::get('locale', Config::get('app.locale'));
App::setLocale($locale);
return $next($request);
}
}
And added in Kernel.php:
\App\Http\Middleware\Locale::class,
\Illuminate\Session\Middleware\StartSession::class,
You can set a route to configure the locale (see Configuring The Locale), and redirect back to the previous url:
Route::get('locale/{locale}', function ($locale) {
$validLocale = in_array($locale, ['lv', 'ru', 'en']);
if ($validLocale) {
App::setLocale($locale);
}
return back();
});
When visitors select locale, get users to your route:
<div class = "col-lg-5 col-md-5" id = "lang">
<ul id = "lang_menu">
<li class = "language{{ App::isLocale('lv') ? ' active' : '' }}">Latviešu</li>
<li class = "language{{ App::isLocale('ru') ? ' active' : '' }}">Pусский</li>
<li class = "language{{ App::isLocale('en') ? ' active' : '' }}">English</li>
</ul>
</div>
In middleware you must use session obtained from request, not from helper session() or Session::get() !
public function handle($request, Closure $next)
{
if ($request->session()->has('locale') ) {
$locale = $request->session()->get('locale');
App::setLocale($locale);
}
return $next($request);
}

Laravel 5 customizing built in login redirect

I am customizing laravel 5's built in login so that it would redirect to three different paths according to the type column which i added to the users table, i tried altering the handle function of RedirectIfAuthenticated middleware. but it seems that it always finds the home URI.
here is my edited middleware
public function handle($request, Closure $next)
{
if ($this->auth->check() && $this->auth->user()->type == 'patient') {
// return redirect('/home');
return 'PATIENT VIEW';
} elseif ($this->auth->check() && $this->auth->user()->type == 'doctor') {
return 'DOCTOR VIEW';
} elseif ($this->auth->check() && $this->auth->user()->type == 'nurse') {
return 'NURSE VIEW';
}
return $next($request);
}
Im new to laravel 5 and i would really appreciate any help and explanations
RedirectIfAuthenticated is being misused here. That middleware is for when an authenticated user tries to access a page that should only be accessed by guests. For example, if I am a user and I try to view the login or registration forms, it doesn't let me.
I would not mess with the authentication itself... some of it is easily customizable but what you're trying to do is not. I would just let Laravel authenticate them first and then handle what to do after.
/home is the default route users are taken to when they login. Move your if checks to that route controller method. Better yet... if you set things up right you don't need any checks at all.
class HomeController {
public function index()
{
$user = \Auth::user();
return view($user->type . '.dashboard');
}
}
Now you just need views named patient/dashboard.blade.php, doctor/dashboard.blade.php, etc. If you have more complex logic then you might want an actual redirect
return redirect('home/' . $user->type);
Define routes for each of those types
Route::get('home/patient', 'PatientController#dashboard');
Route::get('home/doctor', 'DoctorController#dashboard');
Route::get('home/nurse', 'NurseController#dashboard');
And then do whatever you need to in those controller methods.
Check out the docs in Authentication section
Basically what you need is:
Create the auth routes at app/Http/routes.php:
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Create the login form view:
<!-- resources/views/auth/login.blade.php -->
<form method="POST" action="/auth/login">
{!! csrf_field() !!}
<div>
Email
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
Password
<input type="password" name="password" id="password">
</div>
<div>
<input type="checkbox" name="remember"> Remember Me
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
Manually Authenticate users app/Http/Controllers/Auth/AuthController.php:
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Routing\Controller;
class AuthController extends Controller
{
/**
* Handle an authentication attempt.
*
* #return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password])) {
if (Auth::user()->type == 'patient'){
return redirect()->intended('patientDashboard');
}
if (Auth::user()->type == 'doctor'){
return redirect()->intended('doctorDashboard');
}
}
}
}
Or if you want to keep the logic under RedirectIfAuthenticated middleware you could just fix your code:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
//we have a logged user check if it's patient
if($this->auth->user()->type == 'patient'){
return new RedirectResponse(url('/patient'));
}else if($this->auth->user()->type == 'doctor'){
return new RedirectResponse(url('/doctor'));
}
}
return $next($request);
}
Also you should check out this Entrust package.

Resources