Password Reminder - Change email column - php

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() }}

Related

Error message not appearing on Google Captcha in Laravel application

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

Batch uploading and adding files to the database with Laravel

I want to add and update multiple images over a form with Laravel v5.6.
I am also trying to associate these added pictures with another model. But while adding, I am encountering an SQL error due to the error I made somewhere. Here is that error:
SQLSTATE[HY000]: General error: 1364 Field 'imageable_id' doesn't have a default value (SQL: insert into `images` (`img_url`, `updated_at`, `created_at`) values (public/images/yxJ0BQDFz2dU5wzKk5uNreHlKl4Z5kmXDRfMug8p.png, 2020-12-19 05:43:29, 2020-12-19 05:43:29))
Thank you in advance for your help!
My Service.php model file:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Service extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'slug',
'title',
'content',
'status',
];
use HasSlug;
/**
* Get the options for generating the slug.
*/
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
/**
* Eğer `status` set ediliyorsa...
*
*/
public function setStatusAttribute($value)
{
$this->attributes['status'] = in_array($value, ['on', 'yes', 'ok', 'true']) ? 1 : 0;
}
/**
* Eğer `status` alınıyorsa...
*
*/
public function getStatusAttribute()
{
return $this->attributes['status'] == 1 ? 'on' : null;
}
/**
* Get all of the images for the post.
*/
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
My Image.php model file:
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
/**
* Fillable fields
*
*/
protected $fillable = [
'name',
'desc',
'img_url',
'imageable_id',
'imageable_type',
];
/**
* imageable items
*
*/
public function imageable()
{
return $this->morphTo();
}
}
And ServiceController.php:
public function store(Request $request)
{
session()->flash('status', $request->status);
$request->validate([
'title' => 'required|between:5,255',
'content' => 'required|min:10',
// 'status' => 'accepted',
'files.*' => 'file|image|mimes:jpeg,png|max:2048',
]);
$service = new Service;
$service->title = $request->title;
$service->content = $request->content;
$service->status = $request->status;
$service->save();
if($request->hasFile('files')) {
collect($request->file('files'))->each(function ($file) use($service) {
// return Storage::putFile('public/images', $file);
// $newFile = Storage::putFile('public/images', $file);
$newFile = $file->store('public/images');
/**
*
* I don't know if the method of adding to the database here is correct.
* I'll be grateful to those who propose the truth:
*
*/
$image = new \App\Image;
$image->img_url = $newFile;
// $image->imageable->create($service);
$image->save();
$service->images()->save($image);
});
}
return redirect(route('admin.services.index'))->with('success', trans('Kayıt başarıyla eklendi'));
}
create.blade.php:
<form action="{{ route('admin.services.store') }}" enctype="multipart/form-data" method="POST">
#csrf
#method('POST')
<!-- ... -->
<div class="form-group">
<label for="files">{{ __('Yükelenecek dosya') }}:</label>
<input type="file" name="files[]" multiple id="files" class="form-control-file" placeholder="{{ __('Yüklenecek dosyaları seçin') }}" aria-describedby="files-label">
<small id="files-label" class="form-text text-muted">
{{ __('Yüklenecek dosyalar .png ve .jpg türlerini içermelidir.') }}
</small>
</div>
<!-- ... -->
</form>
When you call $image->save() that Image does not yet have a foreign key set for imageable_id and your database schema says there must be a value for imageable_id.
Don't call $image->save() as the Model will be saved after you call $service->images()->save($image). That will set the foreign key and save the model for you. So when it saves it will have the needed foreign key field with a value.

Argument 1 passed to ...LeadRep::create() must be an instance of ...Entities\Lead, array given, called in .....LeadController.php on line 108

I have tried to insert lead_name,lead_status,lead_description value in db in laravel 6.18.41 version.
Controller code(LeadController.php):
<?php
namespace App\Http\Controllers;
use App\Repository\LeadRep as LeadRepo;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController as BaseController;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
class LeadController extends BaseController
{
private $leadRepo;
public function __construct(LeadRepo $leadRepo)
{
$this->leadRepo = $leadRepo;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entities\Lead'
));
}
/**
* Display a listing of the resource.
* #return \Illuminate\Http\Response
*/
public function index()
{
//$started = microtime(true);
$count = $this->leadRepo->count();
//$end = microtime(true);
//$queryTime = $end - $started;
$lead = $this->leadRepo->findAll();
if (is_null($lead)) {
return $this->sendError('Lead not found.');
}
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($lead, 'json');
return $this->sendResponse($json, 'Leads retrieved successfully.');
//return $this->sendResponse($count . "<-count ... querytime -> " . $queryTime . " ms", 'Leads retrieved successfully.');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
// $validatedData = $request -> validate([
// 'lead_name' => 'required',
// 'lead_status' => 'required',
// 'lead_description' => 'required'
// ]);
/*$validator = Validator::make($input, [
'lead_name' => 'required',
'lead_status' => 'required',
'lead_description' => 'required'
]);*/
/*if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}*/
//$input = $request->all();
Log::info($input);
//$lead = Lead::create($input);
$lead = $this->leadRepo->create($input);
return $this->sendResponse($lead, 'Lead created successfully.');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$lead = $this->leadRepo->findById($id);
Log::info(print_r($lead,true));
if (is_null($lead)) {
return $this->sendError('Lead not found.');
}
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($lead, 'json');
return $this->sendResponse($json,
'Lead retrieved successfully.');
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param Lead $lead
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Lead $lead)
{
$input = $request->all();
$validator = Validator::make($input, [
'id' => 'required',
'lead_name' => 'required',
'lead_status' => 'required',
'lead_description' => 'required'
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$lead = $this->leadRepo->findById($input['id']);
if (is_null($lead)) {
return $this->sendError('Lead cannot be updated. Lead Id not found.');
}
$lead->lead_name = $input['lead_name'];
$lead->lead_status = $input['lead_status'];
$lead->lead_description = $input['lead_description'];
$lead = $this->leadRepo->create($lead);
return $this->sendResponse([], 'Lead updated successfully.');
}
/**
* Remove the specified resource from storage.
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Lead $lead)
{
//$lead->delete();
return $this->sendResponse([], 'Lead deleted successfully.');
}
}
Lead Entity(Lead.php):
<?php
namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
use JsonSerializable;
/**
* #ORM\Entity #ORM\Table(name="lead")
*/
class Lead
{
/** #ORM\Id #ORM\Column(type="integer") #ORM\GeneratedValue */
protected $id;
/** #ORM\Column(type="string") */
protected $lead_name;
/** #ORM\Column(type="string") */
protected $lead_status;
/** #ORM\Column(type="string") */
protected $lead_description;
public function getId()
{
return $this->id;
}
public function getLeadName()
{
return $this->lead_name;
}
public function setLeadName($lead_name)
{
$this->lead_name = $lead_name;
}
public function getLeadStatus()
{
return $this->lead_status;
}
public function setLeadStatus($lead_status)
{
$this->lead_status = $lead_status;
}
public function getLeadDescription()
{
return $this->lead_description;
}
public function setLeadDescription($lead_description)
{
$this->lead_description = $lead_description;
}
}
Lead Repository(LeadRep.php):
<?php
namespace App\Repository;
use App\Entities\Lead;
use App\Entities\Post;
use Doctrine\ORM\EntityManager;
use Illuminate\Support\Facades\Log;
use Doctrine\Persistence\ManagerRegistry;
/**
* Class LeadRep
* #package App\Repository
*/
class LeadRep {
/**
* #var string
*/
private $class = 'App\Entities\Lead';
/**
* #var EntityManager
*/
private $em;
/**
* LeadRep constructor.
* #param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* #param Lead $lead
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function create(Lead $lead)
{
$this->em->persist($lead);
$this->em->flush();
}
/**
* #param Lead $lead
* #param $data
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function update(Lead $lead, $data)
{
$lead->setLeadDescription($data['lead_description']);
$lead->setLeadName($data['lead_name']);
$lead->getLeadStatus($data['lead_status']);
$this->em->persist($lead);
$this->em->flush();
}
/**
* #param $id
* #return object|null
*/
public function findById($id)
{
Log::info("Id info".$id);
return $this->em->getRepository($this->class)->findOneBy([
'id' => $id
]);
}
public function findAll()
{
return $this->em->getRepository($this->class)->findAll();
}
public function count()
{
$criteria = [];
return $this->em->getRepository($this->class)->count($criteria);
}
/**
* #param Lead $lead
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function delete(Lead $lead)
{
$this->em->remove($lead);
$this->em->flush();
}
/**
* #param $data
* #return Lead
*/
public function prepareData($data)
{
return new Lead($data);
}
}
Web Route:
use App\Http\Controllers\Lead;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Route::get('lead/{key}','LeadController#show');
Route::get('lead_all','LeadController#index');
/*Route::get('create_lead/{lead_name}/{lead_status?}/{lead_description?}',function () {
return view('leadview');
});*/
Route::post('lead_create','LeadController#store');
Route::get('create_lead',function () {
return view('leadview');
});
Route::get('student/{key}','StudentController#show');
Route::get('student_all','StudentController#index');
Blade View file(leadview.blade.php):
<form method="POST" action="http://127.0.0.1:8000/lead_create" accept-charset="UTF-8">
#csrf <!-- {{ csrf_field() }} -->
<div class="row">
<div class="form-group col-lg-6 ">
<label for="name" class="control-label">Your lead_name</label>
<input class="form-control" placeholder="" name="lead_name" type="text" id="name">
</div>
<div class="form-group col-lg-6 ">
<label for="email" class="control-label">Your lead_status</label>
<input class="form-control" placeholder="" name="lead_status" type="text" id="email">
</div>
<div class="form-group col-lg-12 ">
<label for="message" class="control-label">Your lead_description</label>
<textarea class="form-control" placeholder="" name="lead_description" cols="50" rows="10" id="message"></textarea>
</div>
<div class="form-group col-lg-12">
<input class="btn btn-default" type="submit" value="Send">
</div>
</div>
</form>
I have used doctine with laravel in this project.When submit the form to insert lead value from from,it returning below error,
Argument 1 passed to App\Repository\LeadRep::create() must be an instance of App\Entities\Lead, array given, called in D:\wamp64\www\projects\laraveldemo\crmapp-crud\app\Http\Controllers\LeadController.php on line 108
How can i solve this issue? Can anyone provide solution for this?
The problem is you pass the array of inputs instead of model.
You have function prepareData inside the repo, so you can use it to prepare the model.
$lead = $this->leadRepo->prepareData($input);
$this->leadRepo->create($lead);
UPD
/**
* Class LeadRep
* #package App\Repository
*/
class LeadRep
{
/**
* #param $data
* #return Lead
*/
public function prepareData(array $data): Lead
{
$lead = new Lead();
$lead->setLeadName($data['lead_name']);
$lead->setLeadStatus($data['lead_status']);
$lead->setLeadDescription($data['lead_description']);
return new $lead;
}
}
$lead = $this->leadRepo->create(new LeadRep($lead));
You must pass an instance of a model you are creating.
I changed controller function like below, then added this line in top of controller file - use App\Entities\Lead; ,then it worked.
public function store(Request $storeRequest)
{
$storeRequest->validate([
'lead_name' => 'required',
'lead_status' => 'required',
'lead_description' => 'required'
]);
$lead = new Lead();
$lead->setLeadName($storeRequest->get('lead_name'));
$lead->setLeadStatus($storeRequest->get('lead_status'));
$lead->setLeadDescription($storeRequest->get('lead_description'));
$this->leadRepo->create($lead);
return $this->sendResponse($lead, 'Lead created successfully.');
}

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)

I cannot get the "remember me" function on Laravel to work

In my application I have made a login with “remember me” functionality. When I connect to the application with “remember me” it creates a remember token in the cookies. However, when I test and close the navigator with and without the remember me it behaves the same way.
I have read about Auth::viaRemember(), but I don’t know how to use it.
Here is my login:
public function postLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
{
return Redirect::to('login')->withErrors
($validation)->withInput();
}
$credentials = Input::only('email', 'password');
$remember = (Input::has('remember')) ? true : false ;
$email = Input::get('email');
$username = DB::table('users')
->where('email','LIKE',$email)
->pluck('email');
if( is_null($username)){
Session::flash('message', 'Votre login est invalide');
return Redirect::to('login');
}
else if (Auth::attempt($credentials, $remember)) {
return Redirect::intended('/');
}
else{Session::flash('message', 'Votre mot de passe est incorrect, veuillez réessayer'); }
return Redirect::to('login');
}
the view controller:
public function index()
{
if (Auth::check())
{
$theme = Theme::all();
$questions = questionList::paginate(10);
$the = "";
return View::make('home.home')
->with('user',Auth::user())
->with('theme', $theme)
->with('the' , $the)
->with('questions',$questions);
}
else
{
return Redirect::to('login')->with('message',"Vous devez vous connecter d'abord");
}
}
my user model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* 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('password');
/**
* 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->password;
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}

Categories