Default value selected in bootstrap button after logging out of app at login page - laravel

I want in my login form that when I logout of the app and redirect to login form page again, I want the office auto selected by default which i choose at the last time when logged in.
I am having the following button code in laravel login.blade.php
<input type="hidden" name="office_id" class="office_id" value="0">
<button type="button" class="btn btn-default office_name">Select Office</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
#foreach($offices as $office)
<li>{{$office->name}}</li>
#endforeach
</ul>
</div>
These are the login and logout functions which I am using in loginController.php
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
'office_id' => 'required',
]);
if($user = User::where('email', $request->email)->get()->first()){
$office = Employee::with('office')->findOrFail($user->id);
$office_id = $office['office'][0]['id'];
if($request->office_id == $office_id){
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
return redirect()->intended(route('admin.dashboard', compact('office_id')));
}
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors(['Incorrect Password', 'The Message']);
}
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors(['Select your office to log in', 'The Message']);
}
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors(['Invalid Email', 'The Message']);
}
public function adminLogout(){
Auth::guard('admin')->logout();
return redirect(route('admin.login'));
}

I believe you could achieve this with cookies. You set the time they stay active unlike the session.
Laravel has a cookie interface-
https://laravel.com/docs/5.5/requests#cookies
Cookies using PHP-
https://secure.php.net/manual/en/function.setcookie.php

Related

livewire wire:click not working after adding livewire middleware group

I am doing multistep registration in laravel using livewire
everything was going well before adding my custom guards to the livewire middleware
'middleware_group' => ['web', 'auth:influencer,business'],
note that if i remove the ['auth:influencer,business'] it works well but I need it later in some pages after login so i cant remove it
here is the function that is not fired on click
public function firstStepSubmit()
{
$validatedData = $this->validate([
'name' => 'required|string|max:255|unique:businesses|alpha_num',
'email' => 'required|string|email|max:255|unique:businesses',
'password' => 'required|string|confirmed|min:8',
'password_confirmation' => 'required|string',
]);
$this->currentStep = 2;
}
and here is the button that should fire this function
<button class="btn btn-primary nextBtn pull-right" wire:click="firstStepSubmit" type="button">
<span class="align-middle d-sm-inline-block d-none me-sm-1 me-0">Next</span> <i class="bx bx-chevron-right bx-sm me-sm-n2"></i>
</button>
I don't know if the middleware added is added to all livewire components and if so how to avoid it in this component
Thank you in advance for your help

How to let users change their own passwords in Laravel 7.x?

There are numerous posts about how to allow users to change their passwords, but many of these are for older version of Laravel. What is the correct way for Laravel v7.x in 2020?
Firstly, let's create a form for the user.
A couple of notes on this form:
I have kept the form as simple as possible to make it readable - the CSRF token gets created automatically by Form::open
You should only use 'password' as field name where password managers should autofill it. Some answers suggest using 'password' as the new password field name, which creates a really bad UX
{{Form::open(array('url' => '/account/change-password'))}}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<div class="row">
<div class="col">
<label for="password" class="control-label">Current Password</label>
</div>
<div class="col">
{{Form::password('password', array('id' => 'password', 'class' => 'form-control', 'placeholder' => 'Password'))}}
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="new-password" class="control-label">New Password</label>
</div>
<div class="col">
{{Form::password('new-password', array('id' => 'new-password', 'class' => 'form-control', 'placeholder' => 'New Password'))}}
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="new-password-confirmation" class="control-label">Re-enter
Password</label>
</div>
<div class="col">
{{Form::password('new-password-confirmation', array('id' => 'new-password-confirmation', 'class' => 'form-control', 'placeholder' => 'Confirm Password'))}}
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">Change Password</button>
</div>
{{Form::close()}}
Now in the controller you want to handle the request, let's change the password.
A couple of notes about this:
We validate that the password is not a common one - the list used here is not exhaustive (and all lowercase) and I suggest you update it with the common passwords that are equal to or above your minimum length
Speaking of min length, 8 characters should be your starting point in this day and age
Lastly, don't validate the length of the password confirmation - it'll just give you two errors (since it is already being done)
Finally, this doesn't audit the password change. Use something like Laravel Auditing or even just send an email.
Account.php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
/**
* Change users password
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function changePassword(Request $request)
{
if(Auth::Check())
{
$requestData = $request->All();
$validator = $this->validatePasswords($requestData);
if($validator->fails())
{
return back()->withErrors($validator->getMessageBag());
}
else
{
$currentPassword = Auth::User()->password;
if(Hash::check($requestData['password'], $currentPassword))
{
$userId = Auth::User()->id;
$user = User::find($userId);
$user->password = Hash::make($requestData['new-password']);;
$user->save();
return back()->with('message', 'Your password has been updated successfully.');
}
else
{
return back()->withErrors(['Sorry, your current password was not recognised. Please try again.']);
}
}
}
else
{
// Auth check failed - redirect to domain root
return redirect()->to('/');
}
}
/**
* Validate password entry
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function validatePasswords(array $data)
{
$messages = [
'password.required' => 'Please enter your current password',
'new-password.required' => 'Please enter a new password',
'new-password-confirmation.not_in' => 'Sorry, common passwords are not allowed. Please try a different new password.'
];
$validator = Validator::make($data, [
'password' => 'required',
'new-password' => ['required', 'same:new-password', 'min:8', Rule::notIn($this->bannedPasswords())],
'new-password-confirmation' => 'required|same:new-password',
], $messages);
return $validator;
}
/**
* Get an array of all common passwords which we don't allow
*
* #return array
*/
public function bannedPasswords(){
return [
'password', '12345678', '123456789', 'baseball', 'football', 'jennifer', 'iloveyou', '11111111', '222222222', '33333333', 'qwerty123'
];
}

Unable to get input data from Form submit GET request in laravel 5.1 [duplicate]

This question already has answers here:
Can't retrieve url GET parameters with Laravel 5.1on remote server
(2 answers)
Closed 2 years ago.
I have a search form that is sending a GET request to the method that it is using to view the form:
<form class="form-horizontal" method="GET" action="{{ route('LoggedIn.StudentModule.StudentHomeWork.index') }}">
<div class="form-group form-group-sm">
<div class="col-sm-3">
<input type="text" name="inputdate" class="form-control datepicker" placeholder="Date" >
</div>
<div class="col-sm-2">
<button class="btn btn-primary btn-sm btn-block" type="submit">
<i class="fa fa-search" aria-hidden="true"></i>
Search
</button>
</div>
</div>
</form>
And the route:
Route::group(array(
'middleware' => 'auth',
'prefix' => '!',
'namespace' => 'LoggedIn',
'as' => 'LoggedIn.',
), function() {
.................
Route::group(array(
'prefix' => 'StudentModule',
'namespace' => 'StudentModule',
'as' => 'StudentModule.'
), function () {
............
Route::group(array(
'prefix' => 'StudentHomeWork',
'as' => 'StudentHomeWork.',
), function () {
Route::get('/', array(
'as' => 'index',
'uses' => 'StudentHomeWorkController#index'
));
});
..................
});
...............
});
And my controller:
public function index()
{
$searchParam = request('inputdate') ? request('inputdate') : date('Y-m-d');
echo $searchParam; // this is showing no data
}
The problem is, i couldn't get the data from submitted form. I have used every option that i found in stackoverflow but couldn't get the data. Can anyone point me out what i am missing! My laravel version is 5.1
Note: I am using this method in Laravel 5.8 + 6. Which is working just fine
Try This
How To Pass GET Parameters To Laravel From With GET Method ?
Route::get('any', ['as' => 'index', 'uses' => 'StudentHomeWorkController#index']);
Then Controller
public function index(){
$searchParam = Input::get('category', 'default category');
}
Form:
{{ Form::open(['route' => 'any', 'method' => 'GET'])}}
<input type="text" name="inputdate"/>
{{ Form::submit('submit') }}
{{ Form::close() }}
There Also various method...
Change it as your need.. You can also pass it in url like:
Route::get('any/{data}','StudentHomeWorkController#index')->name('something);
Controller:
public function index($data){
print_r($data);
}
Hope it will help

Validator in Laravel 5.6 not delivering $error messages

I am coding in Laravel 5.6 and i have a layout file called errors.blade with the contents of:
#if(session('status'))
<div class="alert alert-dismissible alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ session('status') }}
</div>
#endif
#if(count($errors))
<div class="alert alert-dismissible alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
#foreach($errors as $error)
<ul>
<li>{{ $error }}</li>
</ul>
#endforeach
</div>
#endif
And my controller that insterts data into db and uses the $this->validate is:
public function store()
{
$this->validate(request(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'username' => 'required',
'password' => 'required|confirmed',
'discord' => 'required'
]);
Admin::create([
'first_name' => request('first_name'),
'last_name' => request('last_name'),
'email' => request('email'),
'username' => request('username'),
'password' => bcrypt(request('password')),
'discord' => request('discord'),
]);
return redirect('/admin/login')->with('status', 'Install successfully completed. Use the form below to login to your account.');
}
As you can see i am sending back a session with the name of status which i have setup to show in my errors file, which works perfectly. But as soon as i leave a field blank or mismatch the passwords on purpose i get this from the actual $errors:
This is happening on all pages. I don't know what exactly is the problem. The status messages work, but the error message here doesn't work. It happens with any error with validator or even with the:
return redirect()->route('admin-login')->withErrors('Incorrect
Username or Password.');
Just a little more info, i am using a guard for admin and guard for the default laravel web to separate sessions of admin and regular users. I don't know if this could be any of the cause. Any help is greatly appreciated to remove this road block for me and any other users who have ran or may run into this.
Change the #foreach to this:
#foreach($errors->all() as $error)

How to pass in user id into foreach loop?

I'm a novice when it comes to PHP and Laravel and am embarrassed that I haven't figured this out yet. I'm trying to provide an option for my user to import their database into the application. However, I need to attach a user id to each row so it can be saved with that user. I've tried multiple attempts to grab that user id and pass it into the foreach loop so it can be saved. Any guidance I can receive, I'd be most grateful. I am using Maatwebsite/Laravel-Excel facade.
Here is my Controller:
class ImportController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
$insert[] = [
'user_id' => $value->user_id,
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
}
Here is my route:
Route::post('importExcel', 'ImportController#importExcel');
Here is my view:
<button type="button" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#importExcel">Import</button>
<div class="modal fade" id="importExcel" tabindex="-1" aria-labelledby="importExcelLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Import Your Database</h4>
</div>
<div class="modal-body">
<p>Click browse to import your database. Only Microsoft Excel extensions are acceptable. Please label your columns as follows:</p>
<ul>
<li>user_id (leave this column empty)</li>
<li>first_name</li>
<li>last_name</li>
<li>title</li>
<li>level</li>
<li>company</li>
<li>address_1</li>
<li>address_2</li>
<li>city</li>
<li>state</li>
<li>zip_code</li>
<li>office_tel</li>
<li>mobile_tel</li>
<li>member_since</li>
</ul>
<form action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
<input type="file" name="import_file" />
<input type="hidden" name="_token" value="{{csrf_token()}}">
<button type="submit" class="btn btn-primary">Import File</button>
</form>
</div><!-- /.modal-body-->
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
</div><!-- /.modal-footer-->
</div><!-- /.modal-content-->
</div><!-- /.modal-dialog-->
</div><!-- /.modal-->
Here is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
protected $fillable = [
'user_id',
'first_name',
'last_name',
'title',
'level',
'company',
'email',
'address_1',
'address_2',
'city',
'state',
'zip_code',
'office_tel',
'mobile_tel',
'member_since' ];
}
First of all: Where do you set $insert? You have to set this variable with the data you like to import. Despite of that you can try the following:
If I understand you right, the database-field user_id should contain the ID of the logged in user - if so, try in your controller the following in importExcel (see comment):
public function importExcel(Request $request)
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
[
'user_id' => $user->id, // Access here the userId of the logged in user
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
Hope that helps :)

Resources