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

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)

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

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']);

Laravel route to add in pivot table works function in model with controller not

Route:
Route::get('/addItemToOrder/{orderId}/{itemId}/{qt}', function ($orderId, $itemId, $qt) {
$order = Order::find($orderId);
$item = Item::find($itemId);
$order->items()->attach($item, ['qt' => $qt]);
});
WORKS Fine.
Pivot model
class ItemOrder extends Pivot
{
//
protected $fillable = [
'order_id',
'item_id',
'qt'
];
static public function create($orderId, $itemId, $qt)
{
$order = Order::find($orderId);
$item = Item::find($itemId);
$order->items()->attach($item, ['qt' => $qt]);
}
Controller
class ItemOrderController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$itemOrders = ItemOrder::all();
return view('itemOrder.index', compact('itemOrders'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
$items = Item::pluck('name', 'id');
$orders = Order::pluck( 'account_id', 'id');
$qt = 0;
return view('itemOrder.create', compact('items', 'orders', 'qt'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ItemOrdersRequest $request)
{
//
ItemOrder::create($request->all());
return redirect('/itemOrder');
}
Request
class ItemOrdersRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'order_id'=>'required',
'item_id'=>'required',
'qt'=>'required'
];
}
}
Blade create
{!! Form::open(['action' =>'App\Http\Controllers\ItemOrderController#store', 'method' => 'post', 'enctype' => 'multipart/form-data']) !!}
{!! form::label('order_id', 'Order_id: ') !!}
{!! form::select('order_id',$orders) !!}
{!! form::label('item_id', 'Item_id: ') !!}
{!! form::select('item_id',$items, null) !!}
{!! form::label('quantity', 'Quantity: ') !!}
{!! form::number('qt',$qt) !!}
{!! form::submit('Add Item to Order') !!}
{!! Form::close() !!}
Error is
Too few arguments to function App\Models\ItemOrder::create(), 1 passed
in
C:\Users\ma\ecom-laravel\app\Http\Controllers\ItemOrderController.php
on line 50 and exactly 3 expected
Laravel Framework 8.38.0
Help please. Thank you.
Instead of $request->all() you have to pass 3 params to ItemOrder::create.
You have defined create method in your model. Better rename to a different name to avoid conflicts between Laravel's default method names.
public function store(ItemOrdersRequest $request)
{
ItemOrder::create($request->order_id,$request->item_id,$request->qt);
return redirect('/itemOrder');
}

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

issue in laravel 4 form data entry to DB

Hello i am trying to create a UI with fname and lname and i want it to be added to my mysql db table.
following are my codes for reference.
**register1.blade.php**
#extends('master')
#section('content')
<div class="row">
<div class="span4 offset1">
<div class="well">
<legend>Please Register Here</legend> <br/>
{{ Form::open(array('url' => 'register1')) }}
#if($errors->any())
<div class="alert alert-error">
×
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</div>
#endif
First Name:{{ Form::text('fname', '', array('placeholder' => 'First Name')) }}<br>
Last Name:{{ Form::text('lname', '',array('placeholder' => 'Last Name')) }}<br>
{{ Form::submit('Submit', array('class' => 'btn btn-success')) }}
<!-- {{ HTML::link('register', 'Sign Up', array('class' => 'btn btn-primary')) }}-->
{{ Form::close() }}
</div>
</div>
</div>
#stop
**HomeController.php**
public function getRegister1()
{
return View::make('home.register1');
}
public function postRegister1()
{
$input = Input::all();
$rules = array('fname' => 'required', 'lname' => 'required');
$v = Validator::make($input, $rules);
if($v->fails())
{
return Redirect::to('register1')->withErrors($v);
} else {
$credentials = array('fname' => $input['fname'], 'lname' => $input['lname']);
if(Auth::attempt($credentials))
{
return Redirect::to('admin');
} else {
return Redirect::to('register1');
}
}
}
**in models-> register.php**
<?php
use Illuminate\Auth\RegisterInterface;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class register extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'register1';
/**
* 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 getFirstName()
{
return $this->fname;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getLastName()
{
return $this->lname;
}
**routes.php**
Route::get('register1','HomeController#getRegister1');
Route::post('register1','HomeController#postRegister1');
when i execute registration it gives me text boxes and submit. onclick of submit i have the following error
**illuminate \ Database \ QueryException**
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fname' in 'where clause' (SQL: select * from `users` where `fname` = sonu and `lname` = k limit 1)
please help me out with this issue.
It's throwing error because there is no fname column in users table. You should check your database structure, and make sure fname column exist.
Assuming you have a register table with all the necessary columns, you would need to tell your app to use that table for authentication. So in `app/config/auth.php', depending on which driver you're using, you'll need entries like the following:
'model' => 'register',
if you're using the 'eloquent' driver, or
'table' => 'register1'
if you're using the database driver.
Also, for what little it's worth, conventionally the class names for models are CamelCase and the table names are lowercase and plural. So, in your case, class Register .... and protected $table = registers;.
If the above doesn't get you up and running, maybe try looking through this tutorial: http://laravelbook.com/laravel-user-authentication/.

Categories