Remember me function causes unknown error - php

I want to make Laravel's "remember me" feature. The problem is that, whenever I create a remember_token column, I am unable to log in or register a user, as it gives some unknown error that I cannot find in any way. Also, I have no idea how to apply this functionality with my code.
Login and Registration Form (except that the registration form does not have a checkbox):
<form class="login-form needs-validation" method="POST" action="{{ route('loja.logar') }}" novalidate>
#csrf
<div class="form-group">
<input type="email" id="email" name="email" aria-describedby="emailHelp" placeholder="Email" required>
</div>
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Password" required>
</div>
<div class="custom-control custom-checkbox mr-sm-2">
<input type="checkbox" name="remember" class="custom-control-input" id="remember">
<label class="custom-control-label" for="remember">Remember me</label>
</div>
<button type="submit" id="submit" name="submit">Enviar</button>
</form>
I'm not using Model, just a controller that is the SiteController:
public function logar(Request $req)
{
$data = $req->all();
$user = Auth::attempt(['email' => $data['email'], 'password' => $data['password']]);
$this->validate($req, [
'email' => ['required', 'email'],
'password' => 'required'
]);
if ($user) {
return redirect()->route('loja.index');
} else {
return redirect()->route('loja.login')
->with('status-verification', 'Error. Try again!');
}
}
public function regist(Request $req)
{
$data = $req->all();
$validator = $this->validate($req, [
'email' => [
'required',
'email',
function ($attribute, $value, $fail) {
if (Users::whereEmail($value)->count() > 0) {
echo 1;
}
},
]
]);
if ($validator) {
Users::create([
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
return redirect()->route('loja.register');
}
}
User Table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->unique();
$table->string('email', 191)->unique();
$table->string('password');
});
}

Related

Password always resetting on the first user only [Laravel]?

Im new to laravel and i decided to make a little project to learn a bit and im trying to make a password reset function following this tutorial but the code seems to always update the first user no matter what. Even if user2#gmail.com tries to reset password, the password resets for user1#gmail.com.
Here is the code :
PasswordReset
public function forgotPassword(Request $request)
{
try {
$user = User::where('email', $request->email)->get();
if (count($user) > 0) {
$token = Str::random(40);
$domain = URL::to('/');
$url = $domain.'/reset-Password?token='.$token;
$data['url'] = $url;
$data['email'] = $request->email;
$data['title'] = "Password Reset";
$data['body'] = "Please click the link below to reset ur password";
Mail::send(
'forgetPasswordMail',
['data' => $data],
function ($message) use ($data) {
$message->to($data['email'])->subject($data['title']);
}
);
$datetime = Carbon::now()->format('Y-m-d H:i:s');
PasswordReset::updateOrCreate(
['email' => $request->email],
[
'email' => $request->email,
'token' => $token,
'created_at' => $datetime
]
);
return response()->json(['success' => true, 'msg' => 'Password Reset Sent']);
} else {
return response()->json(['success' => false, 'msg' => 'User not Found']);
}
} catch(\Exception $e) {
return response()->json(['success' => false, 'msg' => $e->getMessage()]);
}
}
public function resetPasswordLoad(Request $request)
{
$resetData = PasswordReset::where('token', $request->token)->first();
if ($resetData) {
$user = User::where('email', $resetData->email)->first();
if ($user) {
return view('resetPassword', ['user' => $user]);
}
}
return response()->json(['success' => false, 'msg' => 'error404']);
}
public function resetPassword(Request $request)
{
$request->validate([
'password' => 'required|string|min:6|confirmed',
'user_id' => 'required|integer'
]);
$user = User::find($request->user_id);
if ($user) {
$user->password = Hash::make($request->password);
$user->save();
PasswordReset::where('email', $user->email)->delete();
return "<h1>Password reset successfully</h1>";
} else {
return "<h1>Error: User not found</h1>";
}
}
view
#if($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<center>
<form method="POST" action="/reset-Password">
#csrf
<input type="hidden" name="user_id" value="{{ $user->id }}">
<input type="password" name="password" placeholder="New Password">
<br>
<br>
<input type="password" name="password_confirmation" placeholder="Confirm Password">
<br>
<br>
<input type="submit">
</form>
</center>
I tried switching between using the token and email to authenticate but that just made the code a mess.
I am new in Laravel too. I started with it 3 months ago. I have to say, I was to much for me to do whole reset password logic on my own at this stage.
So in created new temp project with Breeze (https://laravel.com/docs/9.x/starter-kits#breeze-and-blade), and I tried to understand the reset password by debugging it step by step via xdebug.
Then I implemented same logic in my project and it is working like a charm.
public function forgotPassword(Request $request): RedirectResponse
{
$request->validate([
'email' => 'required|email',
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
if ($status == Password::RESET_LINK_SENT) {
return back()->with('success', __($status));
}
throw ValidationException::withMessages([
'email' => [trans($status)],
]);
}
public function resetPassword(Request $request): RedirectResponse
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('success', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
public function resetPasswordLoad(Request $request): View
{
return view('auth.reset-password', ['request' => $request]);
}
View reset-password.blade.php:
<form method="POST" action="{{ route('password.store') }}">
#csrf
<div class="mx-auto d-block w-100">
<p class="login-form-title py-3">{{__('login.reset_password_header')}}</p>
</div>
<!-- Password Reset Token -->
<input type="hidden" name="token" value="{{ $request->route('token') }}">
<div class="form-floating my-3">
<input type="text" class="form-control" id="email" name="email" placeholder="email" value="{{old('email', $request->email)}}">
<label for="email">{{__('user.email')}}</label>
#error('email')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<div class="form-floating my-3">
<input type="password" class="form-control" id="password" name="password" placeholder="Password" value="{{old('password')}}" required>
<label for="password">{{__('user.password')}}</label>
#error('password')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<div class="form-floating my-3">
<input type="password" class="form-control" id="password_confirmation" name="password_confirmation" placeholder="Repeat your password" value="{{old('password_confirmation')}}" required>
<label for="password_confirmation">{{__('user.repeat_your_password')}}</label>
#error('password_confirmation')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-block mb-4 w-100">{{__('generic.submit')}}</button>
<div class="text-center">
<p>{{__('login.back_to_login')}}</p>
</div>
</form>
View: forgot-password.blade.php
<form method="POST" action="{{route('password.email')}}">
#csrf
<div class="mx-auto d-block w-100">
<p class="login-form-title py-3">{{__('login.forgot_password_header')}}</p>
<p class="login-form-subtitle">
{{__('login.to_reset_your_password')}}
</p>
</div>
<div class="form-floating my-3">
<input type="text" class="form-control" id="email" name="email" placeholder="email" value="{{old('email')}}">
<label for="email">{{__('user.email')}}</label>
#error('email')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-block mb-4 w-100">{{__('generic.submit')}}</button>
<div class="text-center">
<p>{{__('login.back_to_login')}}</p>
</div>
</form>

laravel form, data not storing into the database

this is my blade file
#csrf
name
#if ($errors->has('name'))
{{ $errors->first('name') }}
#endif
<div class="form-group col-md-6">
<label>email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="Enter your email" required autofocus>
#if ($errors->has('email'))
<span class="Enter properly">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group col-md-6">
<label>Mobile-no</label>
<input type="text" name="mobile-no" class="form-control" id="mobile_no" placeholder="Enter your mobile no" required>
#if ($errors->has('mobile-no'))
<span class="Enter 10digits">{{ $errors->first('mobile_no') }}</span>
#endif
</div>
<div class="form-group col-md-6">
<label>Password</label>
<input type="password" name="password" class="form-control" id="password" placeholder="Enter your password" required>
#if ($errors->has('password'))
<span class="Enter properly">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="form-group col-md-6">
<label>Confirm-password</label>
<input type="password" name="confirm_password" class="form-control" id="confirm_password" placeholder="Re-enter your password" >
</div>
<div class="form-group col-md-6" align="center">
<button class="btn btn-success" style="width:80px;">Submit</button>
</div>
</div>
</div>
</form>
#endsection
This is my controller file
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\FormController;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\User;
use Illuminate\Support\Facades;
class FormController extends Controller
{
public function index()
{
return view ('login');
}
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (User::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('Signed in');
}
return redirect("login")->withSuccess('Login details are not valid');
}
public function registration()
{
return view('registration');
}
public function postRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'mobile_no' => 'required',
'password' => 'required|min:6',
'confirm_password' => 'required',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("dashboard")->withSuccess('have signed-in');
}
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
public function dashboard()
{
if(User::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('are not allowed to access');
}
public function signOut()
{
Session::flush();
User::logout();
return Redirect('login');
}
}
//this is my route file
Route::get('dashboard', [FormController::class, 'dashboard']);
Route::get('login', [FormController::class, 'index'])->name('login');
Route::post('post-login', [FormController::class, 'postLogin'])->name('login.post');
Route::get('registration', [FormController::class, 'registration'])->name('register');
Route::post('post-registration', [FormController::class, 'postRegistration'])->name('register.post');
//this is my migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('customRegistration', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('email');
$table->integer('mobile_no');
$table->string('password');
$table->string('confirm_password');
$table->timestamps();
});
}
public function down()
{
Schema::drop('form');
}
}
i created simple laravel login & registration form.laravel is not genrating errors. but it is not stored a data into the database i.e any of data will be not stored in database.

I want to view my page but it keep saying that undefined variable:$jobs [duplicate]

This question already has answers here:
How to pass data to view in Laravel?
(15 answers)
Passing data from controller to view in Laravel
(10 answers)
Laravel how to pass data from controller to blade [duplicate]
(6 answers)
Closed 1 year ago.
I want the user to view another page when the user clicks the button. inside the new page, some information is already fetched from the database. however, I declare everything but it still saying undefined variable.
form.blade.php
#foreach ($jobs as $job)
<form action="{{route('job-apply', $job->$id)}}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group form-group-material a-form-group">
<label class="label">Full name</label>
<input type="text" class="form-control" name="fullname" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Email</label>
<input type="email" class="form-control" name="email" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Phone Number</label>
<input type="tel" class="form-control" name="contact" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Address</label>
<textarea class="form-control" name="address" cols="30" rows="3"></textarea>
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Category</label>
<input type=text class="form-control" name="category" disabled value="{{ $job->category }}" required />
</div>
<div class="form-group form-group-material a-form-group">
<label class="label">Position</label>
<input type="text" class="form-control" name="position" disabled value="{{ $job->position}}" required />
</div>
<div class="form-group control-file a-file">
<input type="file" name="attachment" accept=".doc,.pdf" multiple />
<div class="file-path-wrapper">
<i class="lni lni-paperclip text-primary"></i>
<input class="file-path form-control" placeholder="Add Attachment(.doc;.pdf)" />
</div>
</div>
<button class="btn btn-success" type="submit">Send</button>
</form>
#endforeach
I have an error inside my form.blade
formcontroller
$jobs = Job::get();
$jobs=Job::where('id',$id)->first();
return view('candidate.apply');
Can someone help me because I am new to Laravel? and here is my main page where user click the button and redirect them to the form
<div class="col-md-2">
<div class="slide-btn">
Apply
</div>
</div
jobcontroller
public function index()
{
$jobs = Job::get();
$company = Company::get();
$menu = Menu::get();
$current_menu = 4;
// $jobs = Job::latest()->paginate(5);
$jobs = Job::
join('company', 'company.id', '=', 'jobs.company')
->get();
return view('jobs.joblist', compact('jobs', 'company', 'menu', 'current_menu'));
}
public function create()
{
return view('jobs.create');
}
public function store(Request $request)
{
$request->validate([
'company' => 'required',
'category' => 'required',
'position' => 'required',
'description' => 'required',
'salary_from' => 'required',
'salary_to' => 'required',
// 'status' => 'required|boolean',
]);
Job::create($request->all());
return redirect()->route('jobs.index');
}
public function show($id)
{
return view('jobs.show', compact('job'));
}
public function edit($id)
{
return view('jobs.edit', compact('job'));
}
public function update(Request $request, $id)
{
$request->validate([
'company' => 'required',
'category' => 'required',
'position' => 'required',
'description' => 'required',
'salary_from' => 'required',
'salary_to' => 'required',
]);
$jobupdate=Job::where('id',$id)->first();
$jobupdate->company=$request->company;
$jobupdate->category=$request->category;
$jobupdate->position=$request->position;
$jobupdate->description=$request->description;
$jobupdate->salary_from=$request->salary_from;
$jobupdate->salary_to=$request->salary_to;
$jobupdate->save();
// Job::update($request->all());
return redirect()->route('jobs.index');
}
public function destroy(Job $job)
{
$job->delete();
return redirect()->route('jobs.index');
}
public function active(Request $request)
{
// dd('text');
$job = Job::where('company',$request->jobId)->first();
$activeVal=request()->get('value');
// dd($activeVal);
if($activeVal == 1)
{
$activeVal=1;
}else{
$activeVal=0;
}
$job->status=$activeVal;
$job->save();
$output['success'] = 'success';
return response()->json($output, 200);
}
You need to pass data to the view using the second parameter of view.
$jobs = Job::get();
return view('candidate.apply', ['jobs' => $jobs]);
Add the compact function in laravel on your return statement.
$jobs = Job::get();
return view('candidate.apply', compact('jobs'));

Laravel Register Index not found and create error

i'm using laravel auth for login, register, forget password, etc
and custom view using jquery not vue.js
i'm using Auth Routes() in routes and planning to custom routing to custom my need, everytime i register using my template and route it to route('register') in my view register page, it shows view index does not found how can i custom this view index to my desire view? i could find it in register controller,
here's my register page view
<form action="{{ route('register') }}" method="POST">
#csrf
<div class="form-head">
<img src="assets/images/logo.svg" class="img-fluid" alt="logo">
</div>
<h4 class="text-primary my-4">Sign Up !</h4>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name Here" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Email here" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Enter Password here" required>
</div>
<!-- <div class="form-group">
<input type="password" class="form-control" id="re-password" placeholder="Re-Type Password" required>
</div> -->
<div class="form-row mb-3">
<div class="col-sm-12">
<div class="custom-control custom-checkbox text-left">
<input type="checkbox" class="custom-control-input" id="terms">
<label class="custom-control-label font-14" for="terms">I Agree to Terms & Conditions of Orbiter</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success btn-lg btn-block font-18">Register</button>
</form>
and i also have issue after it shows view index error it doesn't call register function, i checked this in my db and nothing adds up
here's my controller though
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role = Role::select('id')->where('name', 'user')->first();
$user->roles()->attach($role);
return $user;
}
i also tried this but still shows the same error view index does not exist
use RegistersUsers;
public function showRegistrationForm()
{
return view('user-register');
}
``
RegisterController uses a trait called RegistersUsers, which has a method showRegistrationForm(). You can override this method in your RegisterController to return your custom view. For example:
class RegisterController extends Controller
{
use RegistersUsers;
public function showRegistrationForm()
{
return view('custom-view');
}
}
So what you want is to redirect the user to a custom view when the user has registered.
You just need to add this function inside register controller.
protected function registered(Request $request, $user)
{
return redirect('url goes here')
}

Input field not required (nullable) Laravel 5.6

I'm having an issue with my contact form. All the fields are required except for one field. Normally I would in migration insert nullable, but apparently, it doesn't work. I have tried to make a nullable in validation, but this doesn't work either. So I'm a bit confused.
public function up()
{
Schema::create('kontaktforms', function (Blueprint $table) {
$table->increments('id');
$table->string('navn');
$table->string('mobilnr');
$table->string('fastnetnr')->nullable();
$table->string('mail');
$table->string('emne');
$table->text('beskrivelse');
$table->timestamps();
});
}
public function store(Request $request)
{
$this->validate($request, [
'navn' => 'required',
'mobil' => 'required',
'email' => 'required',
'emne' => 'required',
'beskrivelse' => 'required'
]);
$kontakt = new Kontaktform([
'navn' => $request['navn'],
'mobilnr' => $request['mobil'],
'fastnetnr' => $request['fastnetnr'],
'mail' => $request['email'],
'emne' => $request['emne'],
'beskrivelse' => $request['beskrivelse']
]);
$kontakt->save();
Session::flash('success', 'Vi har nu modtaget din besked');
return redirect()->route('kontakt.create');
}
Form
<form id="form-contact" action="{{route('kontakt.store')}}" method="POST">
#csrf
<h1 class="display-4">Kontakt os</h1>
<div class="form-group">
<input name="navn" type="text" class="form-control" placeholder="Dit navn...">
</div>
<div class="form-group">
<input name="mobil" type="text" class="form-control" placeholder="Din mobil">
</div>
<div class="form-group">
<input name="fastnetnr" type="text" class="form-control" placeholder="Evt fastnetnr">
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" placeholder="Din email">
</div>
<div class="form-group">
<input name="emne" type="text" class="form-control" placeholder="Emne">
</div>
<div class="form-group">
<textarea name="beskrivelse" class="form-control" placeholder="Skriv din besked her" rows="4"></textarea>
</div>
<br>
<input type="submit" class="btn btn-primary btn-block" value="Send">
<hr>
</form>
Do migration for nullable field as
$table->string('fieldname')->nullable();
and during validation either by using Validator or FormRequest confirm that you haven't added a required attribute
'fieldname' => 'required|integer'
you must have only
'fieldname' => 'integer'
I am not sure what are you trying to do but the table kontaktforms does not have any field called fastnetnr which you are trying to enter from your controller.
Maybe add the field in the migration, run migration again after rolling back and then try?

Categories