Laravel protected $loginView load the default login view - laravel

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.

Related

I wrote the delete method according to the Laravel documentation, but the data is not deleted

Employees.php file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* #method static find($id)
*/
class Employees extends Model
{
use HasFactory;
protected $table = 'employees';
public $timestamps = false;
}
EmployeesController.php
<?php
namespace App\Http\Controllers;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function employees_salaries()
{
return view('director.employees_salaries');
}
public function employees()
{
$employees = Employees::all();
return view('director.employees', ['employees'=>$employees]);
}
public function destroy($id)
{
$employees = Employees::find($id);
$employees->delete();
return redirect('/director.employees')->with('status', 'Your Data is Deleted');
}
}
employees.blade.php file
<from action="/delete/{{$employee->id}}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-delete btn-form me-3">
Delete
</button>
</from>
route.php file
Route::match(['get', 'post'], '/employees', array(EmployeesController::class, 'employees'))->name('employees');
Route::delete('/delete/{id}', array(EmployeesController::class, 'destroy'))->name('delete');
I cleared the cache but have no idea what the problem is. it looks like I wrote the function correctly
p.s version Laravel 9
mySQL 8
phpMyAdmin
Welcome to SO, i think youre not using the variable you assigned the value into,from controller in your blade view. maybe try to make sure you have the right variable or maybe try to use var dump.
try to put this in your controller b4 parsing value to view, to check whether you get the data you wanted or not
dd('$employees');
make sure you use the variable you assigned in your controller to your view
<?php
namespace App\Http\Controllers;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function employees_salaries()
{
return view('director.employees_salaries');
}
public function employees()
{
$employees = Employees::all();
return view('director.employees', ['employees'=>$employees]); //<< here you name the variable 'employees'
}
public function destroy($id)
{
$employees = Employees::find($id);
$employees->delete();
return redirect('/director.employees')->with('status', 'Your Data is Deleted');
}
}
change this variable in view
<from action="/delete/{{$employee->id}}" method="POST"> //<< this one you use '$employee' instead of '$employees'
#csrf
#method('DELETE')
<button type="submit" class="btn btn-delete btn-form me-3">
Delete
</button>
</from>
there might also be other problem, but for now thats what i can point out.
since im also learning.

Request validation with GET method isn't working in Laravel 8 - Recaptcha

I am trying to integrate recaptcha to a query form, where the user enters only one piece of data and it returns the result that is extracted from the database.
I'm using
https://github.com/anhskohbo/no-captcha
But a validation is needed from the controller
Something like this appears in your documentation
$validate = Validator::make(Input::all(), [
'g-recaptcha-response' => 'required|captcha'
]);
Adjusted it for Laravel 8
But since I have my form in a GET method, I cannot use the validations, so I use your wisdom to be able to achieve the integration with recaptcha
This is my ListadoRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ListadoRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'texto' => 'required',
'g-recaptcha-response' => 'required|captcha',
];
}
}
This is my controller:
namespace App\Http\Controllers;
use App\Models\Listado;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Requests\ListadoRequest;
class ListadoController extends Controller
{
public function index(ListadoRequest $request){
$validated = $request->validated();
//other code
}
This is my web.php
Route::get('/busqueda', [ListadoController::class, 'index'])->name('busqueda');
When I try to enter the form it does not enter and stays on the main page
If I remove the validation line and change ListadoRequest to Request I access my form but obviously the captcha is a lie because it is not required
Update
My view
<form action="{{route('busqueda')}}" method="get">
<input type = "text" class="form-control" name="texto" value="{{$texto}}" >
<br>
{!! NoCaptcha::display() !!}
<input type=submit class="btn btn-primary" value= "Buscar">
</form>
Help pls :(

Laravel Fortify Logout Redirect

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.

Livewire fire method when we type into input element

every users when they went to register our website and they are typing username or email, we want to check real time which username or password exists in our database or not. for implementing this feature i have this input element in blade:
<input type="text" class="form-control"
wire:model.lazy="username"
value="{{old('username')}}">
as i'm not sure this implementation is correct i don't have any method on component.
for example:
public function username($username){
echo "Hey {$username} !";
}
i want to know how we can fire method when we type into input element
The lazy directive modifier on your input prevents a request being sent to the server when the field is updating (150ms default debounce). If you want to provide feedback as they type, remove the lazy modifier.
In order to determine if the username/email is in use, you'll want to hook into the lifecycle of your username property. By this I mean the updatedUsername function which will fire when the value of your username property updates in the Livewire component.
You could do something like the following (works with or without the lazy modifier on the input field):
Livewire view
<div>
<label for="username">Username</label>
<input id="username" name="username" type="text" value="{{ old('username') }}"
wire:model="username">
<p>{{ $availability }}</p>
</div>
Livewire component
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
class RegisterForm extends Component
{
public $username;
public $availability;
public function render()
{
return view('livewire.register-form');
}
public function updatedUsername()
{
if (User::where('email', $this->username)->first()) {
$this->availability = 'That username is already taken';
return;
}
$this->availability = '';
}
}
Hopefully the above is self explanitory.
Just a little note, when you wrote "which username or password exists in our database", I'm a little worried - I hope you don't check that passwords are unique, and I hope you hash them properly through the Hash facade.
The better approach is to define some $rules for your component, and use the built-in validation feature.
Alter your view to check for the validation errorbag instead,
<input
type="text"
class="form-control"
wire:model.lazy="username"
/>
#error('username') {{ $message }} #enderror
Then make your component use validation through the rules() method, and using validateOnly() in your updated() hook.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class RegisterForm extends Component
{
public $username;
public function render()
{
return view('livewire.register-form');
}
public function updated($field)
{
$this->vbalidateOnly($field);
}
/**
* The rules for this component
*/
public function rules()
{
return [
'username' => [
'required',
'min:3',
'unique:users,email',
]
];
}
}
See the official Livewire documentation on validation.

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