I am new and installed Laravel 5.5 and trying to work on login functionality. I am using custom fields to login; user_name and user_password. When I submit I am getting
The email field is required.
The password field is required.
but my fields are user_name and user_password in the user table
Login controller
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectAfterLogout = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Logout, Clear Session, and Return.
*
* #return void
*/
public function logout()
{
$user = Auth::user();
Log::info('User Logged Out. ', [$user]);
Auth::logout();
Session::flush();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
protected function getCredentials(Request $request){
return $request->only('user_name', 'user_password');
}
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<div>
<a class="hiddenanchor" id="signup"></a>
<a class="hiddenanchor" id="signin"></a>
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<form class="form-horizontal" role="form" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<h1>Login Form</h1>
<div>
<input id="email" type="email" class="form-control" name="user_name" value="{{ old('user_name') }}" required autofocus>
</div>
<div>
<input id="password" type="password" class="form-control" name="user_password" required>
</div>
<div>
<button type="submit" name="login" class="btn btn-default submit">Log in</button>
<a class="reset_pass" href="#">Lost your password?</a>
</div>
<div class="clearfix"></div>
<div class="separator"></div>
</form>
</section>
</div>
</div>
</div>
You are using the trait AuthenticatesUsers and it is responsible for validating the data after the user submitted the form. If you take a look at this file, you will see this method:
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
More specifically, as you can see, this method is in charge for calling the validator on the fields name "password" and by the method username(). If you only wanted to custom the username field, you could overwrite the username() method in LoginController class:
public function username()
{
return 'user_name';
}
But since you want to custom both the username field name and the password field name, I suggest that you overwrite the validateLogin() method in the LoginController class:
protected function validateLogin(Request $request)
{
$this->validate($request, [
'user_name' => 'required|string',
'user_password' => 'required|string',
]);
}
Hope that helps.
You must go to app/User.php and change
protected $fillable = [
'name', 'email', 'password',
];
to
protected $fillable = [
'name', 'user_email', 'user_password',
];
It will solve your problem. But i must suggest to you change your view form field to email, password instead of user_name, user_password
Related
The laravel custom exception doesn't work in the livewire component, but I don't know why.
This is the livewire blade:
<div>
<form method="POST" wire:submit.prevent="submit">
#csrf
<div x-data="{ id: #entangle('id') }">
<input id="id" type="text" wire:model="id" x-mask="*">
</input>
</div>
#isset($email)
your email is {{$email}}
#endisset
<button type="submit">submit</button>
</form>
</div>
This is the livewire component
class Form extends Component
{
public $id = '';
public $email;
public function submit()
{
$user = User::find($this->id);
if(!empty($user)){
return $this->email=$user->email;
}
throw new UserNotFoundException;
}
}
This is the UserNotFoundException
class UserNotFoundException extends Exception
{
public function render($request)
{
return response()->view('user-not-found');
}
}
After I submitted a wrong id, the browser didn't change to the 'user-not-found' view.
What do I miss? Any suggestion? Thank you!
Ok so I need some help. I am trying to have the address field from my CreateView form auto populate with the Places API result. So I see 2 options:
Override the address field in the CreateView. Use the address input for Places API as the input into the address field for my model.
Autocomplete the address field in the form, from the output of the address input (Places API lookup).
Any suggestions would be greatly appreciated. I have tried multiple different options and cant seem to get it to actually work correctly.
Thanks.
autocomple.html
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), {types: ['geocode']});
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['address_component']);
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
console.log(place)
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{center: geolocation, radius: position.coords.accuracy});
autocomplete.setBounds(circle.getBounds());
});
}
}
views.py
class PropertyCreateView(CreateView):
model = Property
fields = ['address', 'postal_code', 'price',
'details', 'sales_status', 'property_type']
def form_valid(self, form):
return super().form_valid(form)
detail.html
{% load crispy_forms_tags %}
{% block content%}
<div class="container">
<div class="card o-hidden border-0 shadow-lg my-2">
<div class="card-body p-0">
<div class="row">
<div class="col-lg-12">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">New Property</h1>
</div>
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label>Address: </label>
<div id="locationField">
<input id="autocomplete"
placeholder="Enter your address"
onFocus="geolocate()"
type="text"
name="full_address"
class="form-control"
/>
</div>
</div>
<fieldset class="form-group">
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-primary btn-user btn-block"" type="submit">Add Property</button>
</div>
</form>
<hr>
</div>
</div>
</div>
</div>
</div>
</div>
{% include 'properties_app/autocomplete.html' %}
I am trying pass data from reactjs to django through django rest api by post method but there raising this problem.
I have tested post method through Django-REST Api GUI.It's working perfectly.
My Reactjs component code:
import React, { Component } from 'react'
import './Register.css';
import axios from 'axios'
const REGISTER_URL = 'http://127.0.0.1:8000/api/register/?format=json' // received api ulr...
const initiaState = {
username : '',
email : '',
password: ''
}
class Register extends Component{
constructor(){
super()
this.myRegister = React.createRef()
}
state = {
...initiaState
}
changeHandler = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
submitHandler = (event) =>{
event.preventDefault()
console.log(this.state)
this.myRegister.current.reset()
this.setState({
...initiaState
});
axios.post(REGISTER_URL,this.state)
.then(res =>{
console.log(res)
})
.catch(error =>{
console.log("ERROR::: "+error)
})
}
render(){
return(
<div className="Register-box">
<form ref = {this.myRegister} className="Form" onSubmit={this.submitHandler }>
<div className ="form-group ">
<label htmlFor="username" > Name: </label>
<input
className = "from-control ml-4"
type="text"
placeholder = ' Enter Your Name '
name = "username"
id = "username"
value = {this.state.name}
onChange = {this.changeHandler}
/>
</div>
<div className ="form-group">
<label htmlFor="email" > Email: </label>
<input
className = "from-control ml-4"
type="text"
placeholder = ' Enter Your Email '
name = "email"
id = "email"
value = {this.state.email}
onChange = {this.changeHandler}
/>
</div>
<div className ="form-group">
<label htmlFor="password" className="mr-4"> Password: </label>
<input
className = "from-control ml-2"
type="password"
placeholder = ' Enter Your Password '
name = "password"
id = "password"
value = {this.state.password}
onChange = {this.changeHandler}
/>
</div>
<button className = "btn btn-primary" type="submit" value="Submit"> Submit </button>
</form>
</div>
);
}
}
export default Register;
The error is the server connection error. Make sure you have run your server properly.
Check your IP address is correct or not
As you are running your Django server as debugging/testing mode. Run your server using python manage.py runserver 0.0.0.0:8000 here 8000 is the port number.
I am integrating Facebook Login in my New Laravel 5.1.The user will have the option to manually login by using Facebook Login or the traditional form login.So far I have no problem implementing traditional login
For the Laravel Socialite, I think I already set correctly
composer.json
"laravel/socialite": "^2.0",
config/app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
.........
.........
Illuminate\Html\HtmlServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Laracasts\Flash\FlashServiceProvider::class,
Laracasts\Generators\GeneratorsServiceProvider::class,
AlgoliaSearch\Laravel\AlgoliaServiceProvider::class,
Laravel\Socialite\SocialiteServiceProvider::class,
],
AuthController
<?php
namespace App\Http\Controllers\Auth;
use Socialite;
//use Illuminate\Routing\Controller;
use App\User;
use Validator;
use Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
//temporarily redirected to duterte-run.mendanielle.com
public function getRegister()
{
return view('auth.login');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider()
{
return Socialite::driver('facebook')->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback()
{
// try {
$user = Socialite::driver('facebook')->user();
// } catch (Exception $e) {
// return redirect('auth/facebook');
// }
// $authUser = $this->findOrCreateUser($user);
// Auth::login($authUser, true);
// return redirect()->route('home');
}
routes.php
Route::get('/auth/facebook', 'Auth\AuthController#redirectToProvider');
Route::get('/auth/facebook/callback', 'Auth\AuthController#handleProviderCallback');
// Logging in and out
get('/auth/login', 'Auth\AuthController#getLogin');
post('/auth/login', 'Auth\AuthController#postLogin');
get('/auth/logout', 'Auth\AuthController#getLogout');
login form
<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember Me</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">Login</button>
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<a class="btn btn-link" href="{{ url('/auth/facebook') }}">Login With Facebook</a>
</div>
</div>
</form>
I followed the latest documentation at Laravel.com website,and inside services.php
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('CALL_BACK_URL'),
],
And the .env file
FACEBOOK_CLIENT_ID=1834566497828637244
FACEBOOK_CLIENT_SECRET=9505676d1f50bty7b613baa7b68786op5ba48
CALL_BACK_URL=http://localhost:9090/auth/login
The login button will redirect me to
localhost:9090/auth/facebook
NotFoundHttpException in Controller.php line 269:
Controller method not found.
at Controller->missingMethod('facebook')
at call_user_func_array(array(object(AuthController), 'missingMethod'), array('_missing' => 'facebook')) in Controller.php line 256
at Controller->callAction('missingMethod', array('_missing' => 'facebook')) in ControllerDispatcher.php line 164
at ControllerDispatcher->call(object(AuthController), object(Route), 'missingMethod') in ControllerDispatcher.php line 112
at ControllerDispatcher->Illuminate\Routing{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in RedirectIfAuthenticated.php line 41
So what's the proper way? How do you integrate Socialite in Laravel 5.1?
update
I see this 'weird' result in php artisan route:list
GET|HEAD|POST|PUT|PATCH|DELETE | auth/{_missing} | App\Http\Controllers\Auth\AuthController#missingMethod | guest |
Just under the
| auth/facebook|App\Http\Controllers\Auth\AuthController#redirect
Got it
In controller, instead of
use App\Http\Controllers\Controller;
This is the correct controller
use Illuminate\Routing\Controller;
And I fixed the routes,
Route::get('/auth/facebook/callback','Auth\AuthController#handleProviderCallback');
Should match the call back_url listed in .env file which is
http://localhost:9090/admin
So to correct this
Route::get('/admin','Auth\AuthController#handleProviderCallback');
Needs some tweaks when saving if the user is not listed in database but it works when a registered user logs
I am trying to setup stripe as my payement gateway and having some issue.
I want my user to input their credit card info to be able to charge them later on. (aka creating a customer)
After entering all information and press enter, my customer is created on Stripe.com but the credt card information is not saved (so I cannot charge it later on).
On my database the token is saved and when i try to put a charge on the customer I got an answer from Stripe api "cannot charge, user do not have credit card" ...
Here is my code:
views.py
import stripe
def paiements(request):
stripe.api_key = "sk_test_mytestapikey"
utilisateur = request.user
cc_save = Stripetoken.objects.filter(utilisateur= request.user).exists() #check if the user have already a stripe token.
if request.method == 'POST':
token_cc = request.POST.get('stripeToken') #request.POST['stripeToken'] give me an error.
customer = stripe.Customer.create(
card = token_cc,
description = utilisateur.email,
email = utilisateur.email
)
Stripetoken.objects.create(utilisateur= request.user, token = customer.id , description= request.user.email) #save the customer information and token to charge later on
return HttpResponseRedirect('/frontprop/tb/') # Redirect after POST
args = {}
args.update(csrf(request))
args['cc_save'] = cc_save
return render_to_response('b_param_paiement.html', args)
and my html page:
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('pk_test_withmyid');
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#payment-form').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#toggle").click(function(){
$("#cbinfo").toggle();
});
});
</script>
<form action="/frontprop/tb/param/paiements/" method="POST" id="payment-form"> {% csrf_token %}
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Votre numero de carte bancaire:</span>
<input class="form-control" type="text" size="20" data-stripe="number"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVC:</span>
<input class="form-control" type="text" size="4" data-stripe="cvc"/>
</label>
</div>
<div class="form-inline">
<label>
<span>Expiration (MM/YYYY):</span> <br>
<input class="form-control" type="text" size="2" data-stripe="exp-month"/>
</label>
<span> / </span>
<input class="form-control" type="text" size="4" data-stripe="exp-year"/>
</div>
<br>
<button id="stripebutton" class="btn btn-primary" type="submit">Enregistrer la carte</button>
</form>
FYI: I have followed this https://stripe.com/docs/tutorials/forms
Thank you for your help
You need to create a Plan that is free and assign them to that plan, you can later charge that customer with your one off charges as needed.
As stated by Tom, there was a Javascript problem when loading/posting the form.
I have to move on top right after the stripe.js.
Thank Tom I am all set :)