Laravel cashier "Unable to create Braintree customer" error - laravel

I am trying to create a subscription service using Laravel, Laravel Cashier and Braintree. I get the following error:
Unable to create Braintree customer: Unknown or expired payment_method_nonce.
CVV is required.
Expiration date is required.
Credit card number is required.
Credit card must include number, payment_method_nonce, or venmo_sdk_payment_method_code.
I've done the following in my HTML:
<form class="form-horizontal" role="form" method="POST" action="{{ route('register') }}">
<select name="plan" id="plan" class="form-control">
<option value="">Select plan</option>
<option value="free">Free plan - €0/month</option>
<option value="cool">Cool plan - €10/month</option>
<option value="epic">Epic plan - €100/month</option>
</select>
<div id="dropin-container"></div>
<input type="submit" class="btn btn-primary blue-button" value="Sign Up" style="margin-top: 6px;">
<!-- Load the Client component. -->
<script src="https://js.braintreegateway.com/js/braintree-2.31.0.min.js"></script>
<script>
braintree.setup('{{ $braintreeToken }}', 'dropin', {
container: 'dropin-container'
});
</script>
</form>
then I have the following RegisterController.php. The most important bit is in the create method:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/account';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the application registration form.
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showRegistrationForm()
{
$braintreeToken = \Braintree\ClientToken::generate();
return view('auth.register')
->with('braintreeToken', $braintreeToken)
->with('plan', 'none')
->with('route', 'register');
}
/**
* Handle a registration request for the application.
*
* #param Request|\Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* 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, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'plan' => 'required|in:free,cool,epic'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$limit = 200;
$plan = 'free';
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'plan' => $plan,
'limit' => $limit,
'password' => bcrypt($data['password']),
]);
switch($data['plan'])
{
case 'cool':
$limit = 3000;
$plan = 'cool';
$planID = 'gt8m';
break;
case 'epic':
$limit = 32000;
$plan = 'epic';
$planID = '8v3g';
break;
}
$subscription = $user->newSubscription('main', $planID)->create($data['_token']);
if ($subscription)
{
$user->plan = $plan;
$user->limit = $limit;
$user->save();
}
return $user;
}
}
The error happens when I input the following credit card details (these are supposed to be the test credit card numbers used in the sandbox):
Credit card number: 4111 1111 1111 1111
Expiration date: 08/2018
CVV: 123
I've tried googling the error but nothing useful came up.

Problem was I was using the _token from the post data while I needed to use payment_method_nonce.

Related

Send email when user registering in Laravel

I would like to send an email to a user that kinda says "Account created successfully" when user registration is done. I use tailwindcss ui. Below you can see pictures of controllers. I think I should write the code in the RegisterController. So, when someone registers, the system will automatically send mail to the new user.
Controllers
RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* 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, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
What should I do here?
you can send an email by using the Mail facade with the ::send method. Here follows an example:
$to = 'receiver_name';
$email = 'receiver_address';
$mail_data = array(
//here you can pass data to the email blade view
);
Mail::send('viewname', $mail_data, function ($message) use ($to, $email) {
$message->to($email, $to)->subject('subject text');
$message->from('Sender name');
});
you can send a mail using notification. notify the user when he/she registers to the system. in your RegisterController
use App\Notifications\WelcomeEmail;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->notify(new WelcomeEmail($user));
return $user;
}
now make the notification class with the artisan command
php artisan make:notification WelcomeEmail
and content for your notification class is
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class WelcomeEmail extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->view(
'welcome_email', ['user' => $this->user]
)
->from('support#yourcompany.com', 'Your Company Name')
->subject('Welcome Aboard');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
and finally make a blade file in the views folder welcome_email.blade.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head
<body>
<h1>Hello {{ $user->name }}, Account created successfully</h1>
</body>
</html>
if you don't want to use notification, you can use the Mail facade to send a mail.
use Illuminate\Support\Facades\Mail;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Mail::send('welcome_email', compact('user'), function ($message) use ($user) {
$message->to($user->email, $user->name)->subject('Welcome Aboard');
$message->from('support#yourcompany.com', 'Your Company Name');
});
return $user;
}
if you have set MAIL_FROM_ADDRESS in your env file you can skip the from part in the mail send function.

form request validation in laravel 6 and vue does not triggering anything

I'm working in laravel 6 and vueJs; I want to validate the form request using the custom laravel form request. But it does not trigger any validation error instead gives this error message (500 (Internal Server Error)).
this my code. if anyone could help me would be greatly appreciated.
signup.vue
<template>
<v-container>
<v-form #submit.prevent="signup" class="signup-form">
<v-text-field
label="Name"
v-model="form.name"
type="text"
required
></v-text-field>
<v-text-field
label="E-mail"
v-model="form.email"
type="email"
required
></v-text-field>
<v-text-field
label="Password"
v-model="form.password"
type="password"
required
></v-text-field>
<v-text-field
label="Password_confirmation"
v-model="form.Password_confirmation"
type="password"
required
></v-text-field>
<v-btn type="submit" color="green">signup</v-btn>
<router-link to="/login">
<v-btn color="blue">Login</v-btn>
</router-link>
</v-form>
</v-container>
</template>
<script>
export default {
data() {
return {
form: {
name: null,
email: null,
password: null,
password_confirmation: null
}
}
},
errors: {},
methods: {
signup() {
axios.post('/api/auth/signup', this.form)
.then(res => this.responseAfterLogin(res))
.catch(error => console.log(error.response.data))
}
},
}
</script>
<style>
.signup-form {
margin-top: -120px;
margin-bottom: 15px;
}
</style>
Auth controller:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\SignupRequest;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('JWT', ['except' => ['login', 'signup']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Signup part added manually
*/
public function signup(Request $request)
{
$data = $request->validate([
'name' => 'required',
'email' => 'required|string',
'password' => 'required|string',
]);
User::create($request->all()); // the problem is not bcrypting the password section
// login the registered user
return $this->login($request);
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'username' => auth()->user()->name,
]);
}
}
SignupRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SignupRequest 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 [
'name' => 'required',
'email' => 'required',
'password' => 'required|confirmed',
];
}
}
You must define SignupRequest class on your controller for work defined rules. Example usage for signup function,
public function signup(SignupRequest $request)
{
User::create($request->all()); // the problem is not bcrypting the password section
// login the registered user
return $this->login($request);
}
Also you should define $token variable on login function.
Finally, you can find error details on under storage/logs/ folder files.
I hope this help you.

I just upgraded my laravel app to multiple auth guards, how do i get the value of the agent or admin authenticated user

I am using a multi auth guard for my laravel app and everything seems to be working fine....registration, login etc perfect. but i need to get values of an authenticated user of a specific guard in my views but it kept saying undefined property
Here is the code to my model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Agent extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname', 'lastname', 'aid', 'city', 'state', 'email', 'password', 'bankname', 'accountnumber',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
and for my view :
#extends('layouts.app')
#section('title')
OneNaira© Welcome Back {{ auth()->user()->firstname }}
#endsection
#section('footer')
<!--FOOTER-->
<div class="ui stackable pink inverted secondary pointing menu" id="footer">
<div class="ui container">
<a class="item">© OneNaira, 2019.</a>
<div class="right menu">
<a class="item">
<script>
var todaysDate = new Date();
document.write(todaysDate);
</script>
</a>
</div>
</div>
</div>
#endsection
and for the login controller
<?php
namespace App\Http\Controllers\Agent\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
class LoginController extends Controller
{
/**
* Show the login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('agent.auth.login',[
'title' => 'Welcome Back, Sign Into Your OneNaira Initiative Agent Dashboard',
'loginRoute' => 'agent.login',
'forgotPasswordRoute' => 'agent.password.request',
]);
}
/**
* Login the agent.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function login(Request $request)
{
$this->validator($request);
if(Auth::guard('agent')->attempt($request->only('aid','password'),$request->filled('remember'))){
//Authentication passed...
return redirect()
->intended(route('agent.dashboard'));
}
//Authentication failed...
return $this->loginFailed();
}
/**
* Logout the agent.
*
* #return \Illuminate\Http\RedirectResponse
*/
public function logout()
{
Auth::guard('agent')->logout();
return redirect()
->route('agent.login')
->with('status','Agent has been logged out!');
}
/**
* Validate the form data.
*
* #param \Illuminate\Http\Request $request
* #return
*/
private function validator(Request $request)
{
//validation rules.
$rules = [
'aid' => 'required|exists:agents,aid|min:8|max:191',
'password' => 'required|string|min:4|max:255',
];
//custom validation error messages.
$messages = [
'aid.exists' => 'These credentials do not match our records.',
];
//validate the request.
$request->validate($rules,$messages);
}
/**
* Redirect back after a failed login.
*
* #return \Illuminate\Http\RedirectResponse
*/
private function loginFailed()
{
return redirect()
->back()
->withInput()
->with('error','Login failed, please try again!');
}
}
I figured it out : {{ Auth::guard('agent')->user()->firstname }}

Cant't edit or delete post in laravel project

Hello dear i have an problem when user need too delete or edit post , laravel show error " you can't edit post ... " i use a model and controller in laravel and user "auth" system id for access post for delete or edit now see my work :
Index View
#extends('layouts.app')
#section('content')
#auth
<h6 class="alert alert-dark">Dear Guest {{ Auth::user()->name }} for send a post <a class="btn btn-success" href="{{ route('ads.create') }}">Click</a> Here</h6>
#endauth
#guest
<div class="alert alert-primary">for send a post you can <a class="btn btn-success" href="{{ route('register') }}">Register</a></div>
#endguest
#if(count($adses) > 0)
<div class="row">
#foreach($adses as $ads)
<div class="col-xl-3 col-lg-3 col-md-6 col-sm-12">
<div class="card mb-4">
<img class="card-img-top img-fluid" src="/storage/cover_images/{{$ads->cover_image}}" alt="Card image cap">
<div class="card-body">
<h6 class="card-title">{{ $ads->title }}</h6>
#if(!Auth::guest())
#if(Auth::user()->id == $ads->user_id)
<div class="row">
{!!Form::open(['action' => ['AdsController#destroy', $ads->id], 'method' => 'POST',]) !!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close() !!}
Edit
</div>
#endif
#endif
</div>
</div>
</div>
#endforeach
{{ $adses->links() }}
#else
<p class="alert alert-warning" role="alert">any post !</p>
</div>
#endif
#endsection
Ads Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ads extends Model
{
protected $table = 'ads';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function adses(){
return $this->hasMany('App\Ads');
}
}
Ads Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Ads;
class AdsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$adses = Ads::orderBy('created_at', 'desc')->paginate(16);
return view('ads.index')->with('adses', $adses);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('ads.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, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'image|nullable|max:1999',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$ads = new Ads();
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
$ads->user_id = auth()->user()->id;
$ads->cover_image = $fileNameToStore;
$ads->save();
return redirect('/home')->with('success', 'آگهی شما با موفقیت درج شد .');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$ads = Ads::find($id);
return view('ads.show')->with('ads', $ads);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant edit other user's post');
}
return view('ads.edit')->with('ads', $ads);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'required',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
}
$ads = Ads::find($id);
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
if($request->hasFile('cover_image')){
$ads->cover_image = $fileNameToStore;}
$ads->save();
return redirect('/')->with('success', 'your post is update');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant delete other user's post');
}
if($ads->cover_image != 'noimage.jpg'){
// Delete Image
Storage::delete('public/cover_images/'.$ads->cover_image);
}
$ads->delete();
return redirect('/')->with('success', 'Post Removed');
}
}
Routs
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('/', 'AdsController');
Route::resource('ads', 'AdsController');
now , after send a post and login in system user cant delete or edit her post .
Thank you
auth()->user()->id !== $ads->user_id .
Уou have this line. And if user not login when he creating post, you are will be have user_id == null. Check in DB than user_id?
I solved my problem
if(auth()->user()->id !== $ads->user_id)
Since you're using !==, make sure your user_id is integer

Registration process runs normally but login view is not working laravel authentication

I am new to laravel. i have seen some related posts but i could not find right answer. I made an auth using php artisan make:auth, i have a directory publicPages. I have changed the auth.login view to my custom publicPages.login and publicPages.register. Registration process works fine, inserts the data into users table. but it does not login the user. When i go to login view and enter credentials. It neither give any error nor log the user in. just redirects it to back.
Here are routes:
Route::auth();
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
Route::group(array('namespace' => 'UserControllers'), function()
{
Route::group(['middleware' => ['web']], function() {
Route::group(['middleware' => 'auth'], function () {
Route::get('community', 'UserController#showCommunity');
Route::post('communities', 'UserController#addCommunity');
Route::get('edit/{id}', ['as' => 'edit', 'uses' => 'UserController#editCommunity']);
Route::get('delete/{id}', 'UserController#deleteCommunity');
Route::post('update/{id}', ['as' => 'update', 'uses' => 'UserController#updateCommunity']);
Route::get('create', 'IdeaController#displayPost');
Route::post('idea', 'IdeaController#storePost');
Route::get('users', 'UserController#showUserListing');
Route::get('deleteUser/{id}', 'UserController#deleteUser');
Route::get('delete/idea/{id}', 'IdeaController#deleteIdea');
Route::get('approve/{id}', 'IdeaController#approveIdea');
});
});
Controller:
class UserController extends Controller {
//constructor
public function __construct() {
$this->middleware('auth');
}
I know when i would use $this->middleware('auth'); it would redirect to login page for every UserController function. which is working fine.
View:
<form id="login-form" class="clearfix" action="{{url('/login')}}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<p class="rs pb30">Please Provide your Credentials to Verify Your Identity</p>
<div class="form form-post-comment">
<div class="fa-align-center">
<label for="login_email">
<input id="login_email" type="email" name="email" class="txt fill-width txt-name{{ $errors->has('email') ? ' has-error' : '' }}" placeholder="Enter Your Email" required="required"/>
</label>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
<br><br>
<label for="password">
<input id="password" type="password" name="login_password" class="txt fill-width txt-email" placeholder="Enter Your Password" required="required"/>
</label> <br><br>
<label for="links">
Forgotten Password?
<p>Don't have an account? Register Here </p>
</label>
</div>
<div class="clear"></div>
<p >
<span id="response"></span>
{{--<input type="submit" class="btn btn-submit-comment" value="Login">--}}
<button class="btn btn-submit-comment" form="login-form">Login</button>
</p>
</div>
Here is AuthenticatesUsers file:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
//use App\Http\Requests\UserRequest;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function getLogin()
{
return $this->showLoginForm();
}
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$view = property_exists($this, 'loginView')
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {
return view($view);
}
return view('publicPages.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
return $this->login($request);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Get the failed login message.
*
* #return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password');
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
return $this->logout();
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
/**
* Get the guest middleware for the application.
*/
public function guestMiddleware()
{
$guard = $this->getGuard();
return $guard ? 'guest:'.$guard : 'guest';
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function loginUsername()
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* #return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(static::class)
);
}
/**
* Get the guard to be used during authentication.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
is There anything i need to change in postLoginForm() ? Thanks
update 2:
I have changed postLoginForm() function's code to
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
} else {
echo 'not logged in';
}
now finally it prints not logged in but even i use true credentials it says not logged in,
Try to remove web middleware from routes.php, because it applies automatically since 5.2.27 and if you apply it manually it can cause errors similar to yours.
According to your routes file, your login route is /auth/login not /login. So I suggest you to change the action in your view file as:
action="{{url('/auth/login')}}"
EDIT
Since Route::auth(); is already added at the top of your routes file,
you do not need following in your routes file:
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
Please remove that and revert the url in login form.

Resources