Laravel 4 error passing not working - php

I am trying to make a authentication system and the only issue that I am having is that it will not display the errors if the wrong creds are used. It shows the error when one of the fields is empty but not when they are both filled with wrong info. Can someone help me figure out what is wrong? Thanks for all the help!
Here is my view
{{ Form::open([
"route"=>"user/login",
"autocomplete"=>"off"
]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), [
"placeholder"=>"Username"
]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", [
"placeholder"=>"Password"
]) }}
#if($error = $errors->first("password"))
<div class="error">
{{ $error }}
</div>
#endif
{{ Form::submit("Login") }}
{{ Form::close() }}
here is the controller
<?php
use Illuminate\Support\MessageBag;
class UserController extends BaseController
{
public function loginAction()
{
$errors = new MessageBag();
if($old = Input::old("errors")) {
$errors = $old;
}
$data = [
"errors"=>$errors
];
if(Input::server("REQUEST_METHOD") == "POST") {
$validator = Validator::make(Input::all(), [
"username"=>"required",
"password"=>"required"
]);
if($validator->passes()) {
$credentials = [
"username"=>Input::get("username"),
"password"=>Input::get("password")
];
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
} else {
echo "Login failed";
$data["errors"] = new MessageBag([
"password"=>[
"Username and/or password invalid."
]
]);
$data["username"] = Input::get("username");
return Redirect::route("user/login")
->withInput($data);
}
}
return View::make("user/login", $data);
}
}

It looks like you are not displaying any message if the authentication fails. Auth::attempt() will try to match the username and password and if it fails it should add something to the errors array.
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
else // add this
{
echo 'login failed - username and/or password provided are not correct';
}
That said, you probably need to add an else statement here.

Related

How to show error message if user does not exist

I am trying to fetch details of some user based on id, if id does not exist in database, how to handle error in that case and how can i show some error message for assets/lang/en/somefile.php , saying that 'errorMessage' => 'Some error occured.Please try again!.',
$city=City::with('locations')->findOrFail($id);
// if $id does not exit how to handle error
// how to show message form asses/lang/en/somefile.php to user.
// like "please try again"
return view('admin.city.viewCity',compact('city'));
With laravel you can pass error to view like this,
controller,
Redirect::back()->withInput()->withErrors(['msg' => 'try again']);
view,
<ul class="errors">
#foreach ($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
You can just use find() instead of findOrFail(). Controller's method should looks like...
public function methodName(Request $request, $id)
{
$city = City::with('locations')->find($id);
if ($city === null) {
return redirect()->back()->withErrors(['msg' => 'Can not find city.']);
} else {
return view('admin.city.viewCity', [
'city' => $city,
]);
}
}
Or shorter version:
return $city === null
? redirect()->back()->withErrors(['msg' => 'Can not find city.'])
: view('admin.city.viewCity', [
'city' => $city,
]);
Please try this
$city = City::with('locations')->findOrFail($id);
if(count($city) > 0 ){
return view('admin.city.viewCity',compact('city'))
}else{
return view('your message inside balde')
}
or
$city = City::with('locations')->findOrFail($id);
if(count($city) > 0 ){
return view('admin.city.viewCity',compact('city'))
}else{
$errorMessage = "User not found";
return view('admin.city.viewCity',compact('errorMessage'))
}
Please try this what I have done before
if(!$city->isEmpty()){
return view('single', compact('city'));
}else{
return view('nodata', compact('city'));
}
noted: nodata it mean your blade view to show message error to user

Laravel 5.4 add a message to validator's errors

So I am receiving data from a form that should reset user passwords:
Old Password: |field|
New Password: |field|
Confirm Password: |field|
And i want to be able to display a message out for the user if his old password does not match what he entered in the first field. I don't want to make an entirely new validation method and just want to throw an error to the use when i make my own if(). So how do I achieve this using the $errors variable that is available in my blade views
So here is an example of my controllers method
public function update(Request $request){
$this->validate($request,[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
$user = Auth::user();
if(password_verify($request->newPass,$user->password)){
$user = User::find($user->id);
$user->password = bcrypt($request->newPass);
$user->save();
}else{
//the code for adding a new key to $errors variable
return back(); Or return redirect('path');
}
}
So in the view I want to this
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
You can do this in your controller:
$validator = Validator::make($request->all(),[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
And then before your return back();, add:
$validator->after(function($validator) {
$validator->errors()->add('tagName', 'Error message');
});
With your message.

laravel validation callback not work

i'm trying to use callback to simply to check my form input, the offical code is here: https://laravel.com/docs/5.2/validation
the following is my function
public function addthread(Request $request) {
$input = $request->all();
$rules = array('title' => 'required|unique:thread|max:255');
$message = array('title.required' => 'The :attribute field is aaa required.');
$validator = Validator::make($input, $rules, $message);
$validator->after(function($validator) {
if ($this->checkOpt()) {
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
});
if ($validator->fails()) {
return redirect('addthreadhtml')->withErrors($validator)->withInput();
}
}
public function checkOpt() {
return false;
}
the blade tpl:
#if (count($errors) > 0)
<div class="container" stytle="max-width:80%">
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
The num_opt error never print out, any idea?
checkOpt() is returning FALSE, so the code will never enter the if statment.
if ($this->checkOpt()) { // this is returning false, right ?? so, its not adding the error
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
Your checkOpt() always returns false, so your condition won't ever be satisfied.

Laravel Redirect with

I got a problem when trying to redirect back with some results from my sql.
I got a function:
public function postSearch() {
$validator = Validator::make(Input::all(), array(
'search' => 'required'
)
);
if($validator->fails()) {
return Redirect::route('search')
->withErrors($validator)
->withInput();
} else {
$search = Input::get('search');
$user = User::where('username', 'like', '%' . $search . '%')->get();
if($user->count() >= 1) {
return Redirect::route('search')
->with('user', $user)
->withInput();
} else {
return Redirect::route('search')
->with('global', 'Could not find user.')
->withInput();
}
}
return Redirect::route('search')
->with('global', 'Something went wrong, try again later.');
}
but when select was successful in other my file with this code:
#foreach ($user as $users)
<p>
$users->username;
</p>
#endforeach
i got exception undefined user variable. But when i trying to search what doesnt exists in table, 'global' attribute showing my message.
Any ideas why is that not working?
Well, your error is just fine. The $user variable is not defined so you can't iterate over it.
There are 2 things you can do. In your view, you can check if the variable is set
#if (isset($user)
#foreach ($user as $users)
{{ $user->name }}
#endforeach
#endif
You can also set a default value on your code, but you will also need to always your variable to the view. For example:
$user = array();
return Redirect::route('search')
->with('user', $user)
->with('global', 'Could not find user.')
->withInput();
// you will need the $user on your last redirect too
This should fix your problem.

laravel 4 authentication and login not working for me

I'm tearing my hair out over this login problem. Hopefully someone will be able to see this right off the bat and I've just been staring at it too long.
Simply put, I can create a user but can't get the same user logged into the system.
Here is the code that successfully stores the new user…
public function store()
{
//initialise new user
$user = new User();
//fill user object
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->username = Input::get('username');
$user->email = Input::get('email');
//$user->password = Hash::make('password');
$user->password = Hash::make(Input::get('password'));
$user->role_id = '2';
//submit user object
$success = $user->save();
if ($success) {
$user->save();
return Redirect::route('users.index');
}
$errors = $user->errors()->all();
return Redirect::route('users.create')
->withInput()
->withErrors($errors)
->with('message', 'You have errors on your form.');
}
Here is my login form to log in as the above user...
{ Form::open(array('url' => 'login')) }}
<ul>
<li>
{{ Form::label('username', 'Username:') }}
{{ Form::text('username') }}
</li>
<li>
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</li>
<li>
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
</li>
</ul>
{{ Form::close() }}
Here is the route:
Route::post('login', function() {
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
//echo Hash::make('password');
if (Auth::attempt($userdata)) {
echo "success";
}
else {
//print_r($userdata);
echo "fail";
}
});
Unfortunately… when I create a user and attempt to login everything always echoes fail.
Can someone point out what I'm doing wrong?
Thanks.
DS
* ok… corrected above.
Where you have
$user->password = Hash::make('password');
it should be:
$user->password = Hash::make(Input::get('password'));
Your user creation code is giving everyone the password 'password'.

Categories