Error message not appearing on Google Captcha in Laravel application - php

I am trying to implement a Google Captcha on my Laravel site on the login page. I am using Anam Hossain's Captcha plugin. The captcha appears and allows users to login to the site when it is checked, and prevents users from logging in when it is unchecked, however the error message informing users that they must fill out the captcha doesn't appear.
In my AppServiceProvider I have extended the Validator class to create a rule for 'google-captcha', with a number of error codes in a file 'GoogleRecaptcha.php'. The validator function sits in the LoginController where the rules are added. The captcha itself is displayed in the view, login.blade.php. The validator function is called in AuthenticatesUsers.php.
My code is as follows:
// AppServiceProvider.php
Validator::extend('google_captcha', function ($attribute, $value, $parameters, $validator){
$http=Http::asForm()->post(config('google_captcha.gc_verification_url'),[
'secret' => config('google_captcha.secret_key'),
'response' =>$value,
]);
if(!$http->object()->success){
$errorMessage=null;
collect($http->object()->{"error-codes"})->each(function ($item)use(&$errorMessage){
$errorMessage.=config('google_captcha.error_codes')[$item];
});
$validator->addReplacer('google_captcha',
function($message, $attribute, $rule, $parameters) use ($errorMessage) {
return \str_replace(':message', $errorMessage, $message);
}
);
}
// LoginController.php
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::ADMININDEX;
protected $maxAttempts = 5;
protected $decayMinutes = 60;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
$messages = [
'g-recaptcha-response.required' => 'You must complete the captcha',
];
return Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255'],
'password' => ['required', 'string', 'min:8'],
'g-recaptcha-response' => ['required', 'google_captcha']
], $messages);
}
GoogleRecaptcha.php
namespace App\Rules;
use Anam\Captcha\Captcha;
use Illuminate\Contracts\Validation\Rule;
class GoogleRecaptcha implements Rule
{
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$captcha = new Captcha();
$response = $captcha->check(request());
if (! $response->isVerified()) {
dd($response->errors());
}
return $response->isVerified();
}
public function message()
{
return 'Please fill out the captcha.';
}
}
AuthenticatesUsers.php
public function login(Request $request)
{
$this->validator($request->all())->validate();
login.blade.php
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
#captcha()
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
In GoogleRecaptcha.php do I need to return a value to the view?
Any further info would be appreciated.
Thanks,
Regards,
Robert

Related

Create view in one controller and store data in other controller laravel

I'm new to Laravel and I'm trying to store a form. I created the view with the House controller but now I want to store the data in the view with the Booking controller. But when I click the button nothing happens.
My question is if it is possible to make a view with one controller and store it with another controller or maybe there is an other solution.
I also want to use the id of the house to store. How do I get that in the other controller as well?
Web Route
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', [\App\Http\Controllers\HouseController::class, 'index']);
Route::get('house/{house}', [\App\Http\Controllers\HouseController::class, 'show']);
Route::post('house/{house}', [\App\Http\Controllers\BookingController::class, 'store']);
Route::get('rental', [\App\Http\Controllers\HouseController::class, 'getUserHouses']);
Route::get('rental/new', [\App\Http\Controllers\HouseController::class, 'create']);
Route::post('rental/new', [\App\Http\Controllers\HouseController::class, 'store']);
Route::get('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'edit']);
Route::put('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'update']);
Auth::routes();
Booking controller
<?php
namespace App\Http\Controllers;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class BookingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$newBooking = Booking::create([
'user_id' => Auth::id(),
'house_id' => $request->id,
'begin' => $request->begin,
'end' => $request->end,
'status' => 0
]);
return redirect('/');
}
/**
* Display the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function show(Booking $booking)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function edit(Booking $booking)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Booking $booking)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function destroy(Booking $booking)
{
//
}
}
House controller
<?php
namespace App\Http\Controllers;
use App\Models\house;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Helper\Imageable;
use DB;
class HouseController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$houses = House::all();
return view('/home', [
'houses' => $houses
]);
}
/**
* Display a listing of the houses the owner has
*
* #return \Illuminate\Http\Response
*/
public function getUserHouses()
{
$houses = DB::table('houses')
->where('user_id', '=', Auth::id())
->get();
return view('/rental/rental', [
'houses' => $houses
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('rental/new');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$newHouse = House::create([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'user_id' => Auth::id(),
'online' => $online,
'image' => $path,
]);
return redirect('rental');
}
/**
* Display the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function show(house $house)
{
return view(
'/house',
[
'house' => $house
]
);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function edit(house $house)
{
return view(
'rental/edit',
[
'house' => $house
]
);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function update(Request $request, house $house)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$house->update([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'online' => $online,
'image' => $path,
]);
return redirect('rental/edit/' . $house->id);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function destroy(house $house)
{
//
}
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-12">
<h1 class="display-one ">{{ $house->title }}</h1>
<p class=".text-light">{{ $house->place }}, {{ $house->country }}</p>
</div>
</div>
<div class="row mt-5">
<div class="col-sm-6">
<img src="{{ asset("img/houses/$house->image") }}" alt="{{ $house->title }}" class="img-fluid" />
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Kies een datum en reserveer direct</label>
<form method="POST" action="">
#csrf
<input type="date" name="begin">
<input type="date" name="end">
<div class="col-md-12 bg-light mt-3">
<button type="button" class="btn btn-warning ml-2">Vraag aan</button>
</div>
</form>
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-sm-6">
<p class="display-one ">{{ $house->summary }}</p>
</div>
<div class="col-sm-6">
<h2 class="display-one ">Aangeboden door</h2>
<p>Prijs per nacht €{{ $house->price_per_night }}</p>
</div>
</div>
</div>
#endsection
First of all, nothing happens when you click the form submit button because it is currently type="button" and in order this button to play role of submission button it must be type="submit". You can do whatever you want with Laravel. If you want your form to hit another controller method you can simply specify that in your form tag. Like so:
Imagine this is a form inside a view that is rendered by HouseController
<form method="POST" action="{{ url('/save/from/booking/controller') }}">
// ....
</form>
And now on form submission inside a view that is rendered by HouseController, you will actually hit a route that is BookingController responsive for. And here is your route that is being hit by the form
Route::post('/save/from/booking/controller', [BookingController::class, 'store']);

How to show Laravel form validation error as a 'warning' but still be able to pass the validation?

I have created a custom validation rule using php artisan make:rule ResultValidator and used it to check if the value lies within the reference_min and reference_max of the tests table.
This shows the error message properly. However, I want to show the message just as warning and still be able to pass the validation. Is it possible to do it that way? If not what could be the alternative?
ResultValidator.php
<?php
namespace App\Rules;
use App\Models\Test;
use Illuminate\Contracts\Validation\Rule;
class ResultValidator implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$test = Test::where('test_name', $attribute)->get()->first();
return $value > $test->reference_min && $value < $test->reference_max;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'Warning : The value does not lie on the normal range.';
}
}
Controller's store() method:
public function store( Request $request){
$request->validate([
'blood_glucose_f' => ['required', new ResultValidator() ],
]);
Report::create($request);
}
Blade :
<x-auth-validation-errors class="text-danger mb-4" :errors="$errors" />
<form method="POST" action="/test-orders/enter-result">
#csrf
<div class="mb-3">
<label for="blood_glucose_f" class="form-label"> Blood Glucose F </label>
<x-input id="blood_glucose_f" class="form-control form-control-lg"
type="number" name="blood_glucose_f"
:value="old('blood_glucose_f')" />
</div> ...

Laravel: How to give each user different landing pages depending on their id

I am using the basic laravel auth login and registration code. I just added more functionality to the form. I am trying to make each user, as they log in, to be redirected to their own different pages depending on what account type they are. Right now each user is redirected to the home blade on login. how can i change this so they are redirected to each user's custom page? below is my code:
add user blade
#extends('layouts.app')
#section('content')
<div class="container" style="width:60%">
<div class="card">
<div class="card-header">Add New User</div>
<div class="card-body">
{!! Form::open(['action'=>'UserAccountsController#store', 'method'=>'POST']) !!}
#csrf
<div class="form-group row justify-content-center">
{{Form::label('acctyp', 'Account Type',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::select('acctyp',['Adm'=>'Admin','Rcd'=>'Records','Hod'=>'H.O.D','Tch'=>'Teacher','Std'=>'Student'],null,['placeholder'=>'Choose Account...','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('name', 'Name',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('name','',['placeholder'=>'Name','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('surname', 'Surname',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('surname','',['placeholder'=>'Surname','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('gender', 'Gender',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::select('gender',['F'=>'Female','M'=>'Male','O'=>'Other'],null,['placeholder'=>'Choose Gender...','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('dob', 'Date of Birth',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::date('dob','',['class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('email', 'E-mail Address',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::email('email','',['placeholder'=>'E-mail Address','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('userid', 'User I.D',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('userid','',['placeholder'=>'User I.D','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('password', 'Password',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::password('password',['placeholder'=>'Password','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('cpassword', 'Confirm Password',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::password('cpassword',['placeholder'=>'Confirm Password','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::submit('Add User',['class'=>'btn btn-success'])}}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready( function() {
$('#userid').on('change', function() {
$('#password').val($(this).val());
$('#cpassword').val($(this).val());
});
});
</script>
#endsection
login controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
add user conrtoller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserAccountsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$accounts = User::all();
return view('users.index')->with('accounts', $accounts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('users.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'acctyp'=>'required',
'name'=>'required',
'surname'=>'required',
'gender'=>'required',
'dob'=>'required',
'email'=>'required',
'userid'=>'required',
'password'=>'required',
]);
$account = new User;
$account->acctyp = $request->input('acctyp');
$account->name = $request->input('name');
$account->surname = $request->input('surname');
$account->gender = $request->input('gender');
$account->dob = $request->input('dob');
$account->email = $request->input('email');
$account->userid = $request->input('userid');
$account->password = bcrypt($request->input('password'));
$account->save();
return redirect('/users')->with('success', 'New user successfully added!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$account = User::find($id);
return view('users.show')->with('account', $account);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$account = User::find($id);
return view('users.edit')->with('account', $account);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'acctyp'=>'required',
'name'=>'required',
'surname'=>'required',
'gender'=>'required',
'dob'=>'required',
'email'=>'required',
'userid'=>'required',
'password'=>'required',
]);
$account = User::find($id);
$account->acctyp = $request->input('acctyp');
$account->name = $request->input('name');
$account->surname = $request->input('surname');
$account->gender = $request->input('gender');
$account->dob = $request->input('dob');
$account->email = $request->input('email');
$account->userid = $request->input('userid');
$account->password = bcrypt($request->input('password'));
$account->save();
return redirect('/users')->with('success', 'User successfully updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$account = User::find($id);
$account->delete();
return redirect('/users')->with('success', 'User successfully removed!');
}
}
You should follow the below steps for that:
In LoginController.php
Override this method protected $redirectTo = '/home';
So you need to remove the above code and add following code:
public function redirectTo(){
$type = Auth::user()->acctyp;
switch ($type) {
case 'type1':
return '/YOUR PATH';
break;
case 'type2':
return '/YOUR PATH';
break;
default:
return '/YOUR PATH';
break;
}
}
Remember to include class Illuminate\Support\Facades\Auth; in LoginController.php
You can define a redirectTo method on your LoginController and return the path you want them redirected to:
protected function redirectTo()
{
// do your logic to decide where to go and return a path
$user = $this->guard()->user();
if ($user->acctyp == 'something') {
return route('something.dashboard');
}
...
}
When using the redirectTo method, the default setup will try to redirect them to a "intended" URL and fallback to what you return from redirectTo. (Intended would be where they were trying to reach before the auth middleware redirected them to the login page)
If you want full control over the response you can override the authenticated method on LoginController, which comes from the AuthenticatesUsers trait, to return the response you would like:
protected function authenticated(Request $request, $user)
{
// do your logic here and return a redirect
// to where you want them to go to
if ($user->acctyp == 'something') {
return redirect()->route('something.dashboard')
}
...
}

Password Reminder - Change email column

I'm trying to do a Password Reminder in Laravel 4
I've setup the Controller, But keep getting the error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in
'where clause' (SQL: select * from users where users.deleted_at
is null and email is null limit 1
This would be correct as my users' table has the column "user_email" not "email
Is their any particular way that I can change the query that Laravel runs, to a new / different where that says user_email instead of email.
My controller is as follows :
class RemindersController extends Controller {
/**
* Display the password reminder view.
*
* #return Response
*/
public function getRemind()
{
return View::make('users/password_remind');
}
/**
* Handle a POST request to remind a user of their password.
*
* #return Response
*/
public function postRemind()
{
switch ($response = Password::remind(Input::only('email')))
{
case Password::INVALID_USER:
return Redirect::back()
->with('error', Lang::get($response));
case Password::REMINDER_SENT:
return Redirect::back()
->with('status', Lang::get($response));
}
}
/**
* Display the password reset view for the given token.
*
* #param string $token
* #return Response
*/
public function getReset($token = null)
{
if (is_null($token)) App::abort(404);
return View::make('password.reset')->with('token', $token);
}
/**
* Handle a POST request to reset a user's password.
*
* #return Response
*/
public function postReset()
{
$credentials = Input::only(
'email',
'password',
'password_confirmation',
'token'
);
$response = Password::reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
$user->save();
});
switch ($response)
{
case Password::INVALID_PASSWORD:
case Password::INVALID_TOKEN:
case Password::INVALID_USER:
return Redirect::back()
->with('error', Lang::get($response));
case Password::PASSWORD_RESET:
return Redirect::to('/');
}
}
}
Users Model
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait, SoftDeletingTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('user_password', 'remember_token');
protected $dates = ['deleted_at'];
protected $primaryKey = "user_id";
protected $fillable = array('user_email');
public static $rules = array(
'user_firstname' => 'required|alpha',
'user_surname' => 'required|alpha',
'user_email' => 'required|email|unique:users',
'user_password' => 'required',
'user_telephone' => 'required|numeric'
);
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->user_password;
}
public function getEmail() {
return $this->user_email;
}
public function getReminderEmail() {
return $this->user_email;
}
public function getUserByEmail( $user_email )
{
return $this->where('user_email', '=', $user_email)->first();
}
}
and last but not least, My view :
{{ Form::open(array('url' => 'password/remind')) }}
#if (Session::has('error'))
<p style="color: red;">{{ Session::get('error') }}</p>
#elseif (Session::has('status'))
<p>{{ Session::get('status') }}</p>
#endif
<div class="form-group">
<label>Your Email Address</label>
<input name="user_email" type="email" class="form-control" placeholder="Your Email Address" data-error="Please enter your Email Address" value="{{{ Input::old('user_email') }}}" required>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<div class="help-block with-errors"></div>
</div><!-- /.form-group -->
<div class="text-center">
<button type="submit" class="cta">Reset Password</button>
</div><!-- /.text-center -->
{{ Form::close() }}

Laravel Auth::attempt() return false [duplicate]

This question already has answers here:
laravel 4 custom named password column
(4 answers)
Closed 8 years ago.
I have a problem with laravel 4.2 authentication. Auth::attempt() always return false. Hash::check() return false.
I am tired to solve this problem. I read many tutorial and I can't find the solution.
Here are some of my important files:
my auth.php
<?php
return array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
my UserModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model
*
* #var string
*/
protected $table = 'users';
/**
* The primary key used by the model
*
* #var integer
*/
protected $primaryKey = 'UserId';
/**
* The name of the "created at" column
*
* #var string
*/
const CREATED_AT = 'UserCreatedAt';
/**
* The name of the "updated at" column
*
* #var string
*/
const UPDATED_AT = 'UserUpdatedAt';
/**
* The attributes excluded from the model's JSON form
*
* #var array
*/
protected $hidden = array('UserPassword', 'UserRememberToken');
protected $fillable = array(
'UserName',
'UserSurname',
'UserCity',
'UserStreet',
'UserPostalCode',
'UserPostalCity',
'UserDeskPhone',
'UserMobilePhone',
'UserEmail',
'UserPassword',
'UserType',
'UserPermission',
'UserActive'
);
protected $guarded = array('UserId', 'HotelId', 'UserRememberToken', 'UserCreatedAt', 'UserUpdatedAt');
public static $rules = array(
'name'=>'required|alpha|min:2',
'surname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'password'=>'required|alpha_num|between:8,100|confirmed',
'password_confirmation'=>'required|alpha_num|between:8,100'
);
/**
* Get the unique identifier for the user
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user
*
* #return string
*/
public function getAuthPassword()
{
return $this->UserPassword;
}
/**
* Get the e-mail address where password reminders are sent
*
* #return string
*/
public function getReminderEmail()
{
return $this->UserEmail;
}
/**
* Get the remember token for the user
*
* #return string
*/
public function getRememberToken()
{
return $this->UserRememberToken;
}
/**
* Set the remember token for the user
*
* #var string
*/
public function setRememberToken($value)
{
$this->UserRememberToken = $value;
}
/**
* Get the remember token name used by the model
*
* #return string
*/
public function getRememberTokenName()
{
return 'UserRememberToken';
}
/**
* Get the user type
*
* #return integer
*/
public function getUserType()
{
return 'UserType';
}
}
my UserController.php
<?php
class UserController extends BaseController {
/*
|--------------------------------------------------------------------------
| User Controller
|--------------------------------------------------------------------------
*/
/**
* UserController's constructor
*/
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getBackend')));
}
/**
* Show register page for the user
*/
public function getRegister()
{
return View::make('app.user.register');
}
/**
* Action after pressing the register button
*/
public function postCreate() {
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->passes()) {
// validation has passed, save user in DB
$user = new User;
$user->UserName = Input::get('name');
$user->UserSurname = Input::get('surname');
$user->UserEmail = Input::get('email');
$user->UserPassword = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('user/login')->with('message', 'Dodano użytkownika!');
} else {
// validation has failed, display error messages
return Redirect::to('user/register')
->with('message', 'Pojawiły się następujące błędy:')
->withErrors($validator)
->withInput();
}
}
/**
* Show login page for the user
*/
public function getLogin()
{
// Check if we already logged in
if (Auth::check())
{
// Redirect to backend homepage
return Redirect::to('backend')->with('message', 'Jesteś zalogowany!');
}
return View::make('app.user.login');
}
/**
* Action after pressing the login button
*/
public function postLogin()
{
// Get all the inputs
$data = array(
'UserEmail' => Input::get('email'),
'UserPassword' => Input::get('password')
);
// Declare the rules for the form validation
$rules = array(
'UserEmail' => 'required|email|min:6',
'UserPassword' => 'required|between:8,100'
);
// Declare error message for the rules for the form validation
$messages = array(
'UserEmail.required' => 'Adres e-mail nie może być pusty!',
'UserEmail.email' => 'Adres e-mail jest nieprawidłowy!',
'UserEmail.min' => 'Adres e-mail musi mieć minimum 6 znaków!',
'UserPassword.required' => 'Hasło nie może być puste!',
'UserPassword.between' => 'Hasło musi mieć od 8 do 100 znaków!'
);
// Validate the inputs
$validator = Validator::make($data, $rules, $messages);
// Check if the form validates with success
if ($validator->passes())
{
// Try to log the user in
if (Auth::attempt($data))
{
// Redirect to backend homepage
return Redirect::to('backend');
}
else
{
// Redirect to the login page
return Redirect::to('user/login')
->withErrors('Twój adres e-mail lub hasło jest nieprawidłowe!')
->withInput(Input::except('password'));
}
}
// Something went wrong
return Redirect::to('user/login')
->withErrors($validator)
->withInput(Input::except('password'));
}
/**
* Show the profile for the given user
*/
public function getProfile($id)
{
$user = User::find($id);
return View::make('app.user.profile', array('user' => $user));
}
/**
* Show backend homepage
*/
public function getBackend()
{
return View::make('app.backend.start');
}
}
my login.blade.php
#extends('app.user.master')
#section('title')
{{ 'Logowanie' }}
#stop
#section('content')
<div class="container-fluid">
<div id="page-login" class="row">
<div class="col-xs-12 col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
{{--
<div class="text-right">
Need an account?
</div>
--}}
<div class="box">
<div class="box-content">
{{ Form::open(array('url'=>'user/login', 'class'=>'form-signin')); }}
<div class="text-center">
<h3 class="page-header">{{ Config::get('app.name') }} - logowanie</h3>
</div>
#if($errors->has())
<div class="form-group">
<ul>
#foreach ($errors->all() as $error)
<li class="alert">{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label class="control-label">E-mail</label>
{{ Form::text('email', Input::old('email'), array('class'=>'form-control', 'placeholder'=>'E-mail')) }}
</div>
<div class="form-group">
<label class="control-label">Hasło</label>
{{ Form::password('password', array('class'=>'form-control', 'placeholder'=>'Hasło')) }}
</div>
<div class="text-center">
{{ Form::submit('Zaloguj', array('class'=>'btn btn-large btn-primary btn-block')) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
</div>
</div>
#stop
The problem is your $data that you pass to Auth::attempt. You should change
if (Auth::attempt($data))
into
$dataAttempt = array(
'UserEmail' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($dataAttempt))
and add to your User model the following function:
public function getAuthPassword() {
return $this->UserEmail;
}
This is because you need to pass password in array as your password to attempt method (You can read more about it at How to change / Custom password field name for Laravel 4 and Laravel 5 user authentication)

Categories