Laravel 5 validation errors are not showing - php

I am learning Laravel 5 and I have wrote following code for user login. Now I am trying display validation errors messages with this code:
#if(count($errors))
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
but nothing is displaying. :(
Any idea whyerrors are not displaying, If user not enter any value and hit submit button.
Thanks.
routes.php
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['web']], function () {
Route::get('/login', ['as' => 'login', 'uses' => 'AuthController#login']);
Route::post('/handleLogin', ['as' => 'handleLogin', 'uses' => 'AuthController#handleLogin']);
Route::get('/home', ['middleware' => 'auth', 'as' => 'home', 'uses' => 'UserController#home']);
Route::get('/logout', ['as' => 'logout', 'uses' => 'AuthController#logout']);
Route::resource('user', 'UserController', ['only' => ['create', 'store']]);
});
login.blade.php
#extends('layouts.master')
#section('content')
<div class="row">
<div class="col-md-6">
<h2>Log in</h2>
<p>Hi, here you can login to your account.</p>
<br>
#if(count($errors))
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(array('route' => 'handleLogin')) !!}
<div class="form-group">
{!! Form::label('email', 'E-Mail Address') !!}
{!! Form::text('email', null, array('class' => 'form-control','placeholder' => 'example#gmail.com')) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', array('class' => 'form-control')) !!}
</div>
<div>
{!! Form::token() !!}
{!! Form::submit('Sign In' , array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
<br>
</div>
</div>
#endsection
AuthController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class AuthController extends Controller
{
public function login()
{
return view('auth.login');
}
public function handleLogin(Request $request)
{
$this->validate($request, User::$login_validation_rules);
$data = $request->only('email', 'password');
if(\Auth::attempt($data)) {
return redirect()->intended('home');
}
return back()->withInput();
}
public function logout()
{
\Auth::logout();
return redirect()->route('login');
}
}
User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* 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 static $login_validation_rules = [
'email' => 'required|email|exists:users',
'password' => 'required'
];
}

I think you can modify your handleLogin method to send the errors to the view, something like this:
public function handleLogin(Request $request)
{
$validator=$this->validate($request, User::$login_validation_rules);
$data = $request->only('email', 'password');
if(\Auth::attempt($data)) {
return redirect()->intended('home');
}
return back()->withInput()->withErrors($validator->errors());
}
It should work
You can review the solution reading the Laravel Documentation:
https://laravel.com/docs/5.0/validation
Regards!

Why do you not use built-in register function ?
If you want you also could write your own register with Validator https://laravel.com/docs/master/validation
$validator = \Validator::make($request->all(), User::$login_validation_rules);
if($validator->passes()) {
// authenticate...
// If auth failed, add message to validator
$validator->getMessageBag()->add('password', 'Email or password invalid');
}
return redirect()->back()->withErrors($validator)->withInput();
The issue is you only handle input error, if user type invalid email or password, it not show.

laravel 5.2.*
/* app/Http/Kernel.php */
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
/* you need these two Middleware */
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
]
}

I'm adding this for those who might be have the same problem/solution that I did. I am new to Laravel (5.2) and had been experimenting with different facets of authorization and routing. At one point, my LaravelCollective HTML error bag started getting lost. After much frustration I found this -
I had created a routing group for pages requiring Authorization. I placed a forms page in that group. What I forgot to do was to remove the call to the Authorize Middleware from the controller for that page - $this->middleware('auth'); This caused the request to call for authorization twice. It did not force me to log in twice however, it did cause the session to be recreated and all previous save data was lost. I would end up with MANY session files after running the page a few times.

Related

Have a problem with error: The GET method is not supported for this route. Supported methods: POST

Have a problem with error:
The GET method is not supported for this route. Supported methods: POST.
I put in route post method and in form to but idk why it still show errors...
//route
Route::post('posts/{post}/comment', 'CommentController#store');
//controller
class CommentController extends Controller
{
public function store(Request $request, $post_id)
{
$this->validate($request,[
'content' => 'required',
]);
//$post = Post::find($post_id);
$comment = new Comment;
$comment->content = $request->input('content');
$comment->user_id = auth()->user()->id;
//$comment->post()->associate($post);
$comment->save();
return redirect('/posts')->with('success','Post Created');
}
}
//form
{{ Form::open(['method' => 'POST','action' => ['CommentController#store', $post->id]]) }}
<div class="row">
<div class="col-md-12">
{{ Form::label('comment', "Comment:") }}
{{ Form::textarea('content', null, ['class' => 'form-control']) }}
{{ Form::submit('Add Comment', ['class' => 'btn btn-success']) }}
</div>
</div>
{{ Form::close() }}
//web.php
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/services', 'PagesController#services');
Route::resource('posts','PostsController');
Route::post('/posts/{post}/comment', 'CommentController#store');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
I want when I press button for adding a new comment in Posts/show view to send me where need to send and it only gives me an error.
Have you tried $post in public function store(Request $request, $post_id) ??
Please change as below. please make sure whenever you use resource in route, it should always below of other related route.when call to route, it will call posts/{$id}/edit it is get method. for more info please check below blog.
https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers
Route::resource('posts','PostsController');
Route::post('/posts/{post}/comment', 'CommentController#store');
to
Route::post('/posts/{post}/comment', 'CommentController#store');
Route::resource('posts','PostsController');

Add Profile Information in MyAccountController [backpack-laravel]

I thought about adding a page, to change the profile of a user: name, surname, etc.
Bug report
File: MyAccountController.php
function: public function postAccountProfileForm(UpdateRequest $request)
the FormRequest, returns empty
What I did:
DB:
users->Profiles
File Controller: App\Http\Controllers\Auth\MyAccountController
namespace App\Http\Controllers\Auth;
use Backpack\Base\app\Http\Controllers\Auth\MyAccountController as BaseMyAccountController;
use App\Http\Requests\Auth\Account_profileRequest as StoreRequest;
use App\Http\Requests\Auth\Account_profileRequest as UpdateRequest;
use Auth;
use App\Models\Auth\Account_profile;
class MyAccountController extends BaseMyAccountController
{
/**
* Show the user a form to change his personal information.
*/
public function getAccountProfileForm()
{
$user = Auth::user();
$this->data['title'] = trans('backpack::base.my_account');
$this->data['profile'] = Account_profile::getAccount_profilebyId($user->id);
return view('backpack::auth.account.update_profile', $this->data);
}
/**
* Save the modified personal information for a user.
*/
public function postAccountProfileForm(UpdateRequest $request)
{
//var_dump($request);
//die();
//$result = $this->guard()->user()->update($request->except(['_token']));
$result = Account_profile::getAccount_profilebyId($this->guard()->user()['id'])->update($request->except(['_token']));
if ($result) {
Alert::success(trans('backpack::base.account_updated'))->flash();
} else {
Alert::error(trans('backpack::base.error_saving'))->flash();
}
return redirect()->back();
}
}
File Request: App\Http\Requests\Auth\Account_profileRequest
namespace App\Http\Requests\Auth;
use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
class Account_profileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return backpack_auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
// 'name' => 'required|min:5|max:255'
'nome' => 'required|min:5|max:45',
'cognome' => 'required|min:5|max:45',
'sesso' => 'required|min:5|max:45',
'countrys_id' => 'required|numeric',
'regions_id' => 'required|numeric',
//'provinces_id' => 'required|numeric',
//'citys_id' => 'required|numeric',
'users_id' => 'required|numeric',
//'attivo' => 'required|boolean',
//'accetto_condizionigenerali' => 'required|boolean',
//'accetto_marketing' => 'required|boolean',
//'attivo_notifiche' => 'required|boolean'
//continue_13
];
}
/**
* Get the validation attributes that apply to the request.
*
* #return array
*/
public function attributes()
{
return [
//
];
}
/**
* Get the validation messages that apply to the request.
*
* #return array
*/
public function messages()
{
return [
//
];
}
}
File Models: App\Models\Auth\Account_profile
namespace App\Models\Auth;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
use App\Models\Profile;
class Account_profile extends Model
{
use CrudTrait;
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| FUNCTIONS
|--------------------------------------------------------------------------
*/
public static function getAccount_profilebyId($id)
{
return Profile::find($id);
}
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| SCOPES
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| ACCESORS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| MUTATORS
|--------------------------------------------------------------------------
*/
}
File Route: Routes\backpack\Custom
// --------------------------
// Custom Backpack Routes
// --------------------------
// This route file is loaded automatically by Backpack\Base.
// Routes you generate using Backpack\Generators will be placed here.
Route::group([
'prefix' => config('backpack.base.route_prefix', 'admin'),
'middleware' => ['web', config('backpack.base.middleware_key', 'admin')],
'namespace' => 'App\Http\Controllers\Admin',
], function () { // custom admin routes
}); // this should be the absolute last line of this file
Route::group(
[
'namespace' => 'App\Http\Controllers\Auth',
'middleware' => ['web', config('backpack.base.middleware_key', 'admin')],
'prefix' => config('backpack.base.route_prefix'),
],
function () {
// if not otherwise configured, setup the auth routes
if (config('backpack.base.setup_auth_routes')) {
// Authentication Routes...
}
// if not otherwise configured, setup the dashboard routes
if (config('backpack.base.setup_dashboard_routes')) {
Route::get('dashboard', 'AdminController#dashboard')->name('backpack.dashboard');
Route::get('/', 'AdminController#redirect')->name('backpack');
}
// if not otherwise configured, setup the "my account" routes
if (config('backpack.base.setup_my_account_routes')) {
Route::get('edit-account-profile', 'MyAccountController#getAccountProfileForm')->name('backpack.account.profile');
Route::post('edit-account-profile', 'MyAccountController#postAccountProfileForm');
}
});
File Blade: resources\views\vendor\backpack\base\auth\account\update_profile.blade.php
#extends('backpack::layout')
#section('after_styles')
<style media="screen">
.backpack-profile-form .required::after {
content: ' *';
color: red;
}
</style>
#endsection
#section('header')
<section class="content-header">
<h1>
{{ trans('backpack::base.my_account') }}
</h1>
<ol class="breadcrumb">
<li>
{{ config('backpack.base.project_name') }}
</li>
<li>
{{ trans('backpack::base.my_account') }}
</li>
<li class="active">
{{ trans('backpack::base.update_account_info') }} Profile
</li>
</ol>
</section>
#endsection
#section('content')
<div class="row">
<div class="col-md-3">
#include('backpack::auth.account.sidemenu')
</div>
<div class="col-md-6">
<div class="box">
<div class="box-body backpack-profile-form">
{!! Form::open(array('route' => 'backpack.account.profile', 'method' => 'post')) !!}
<div class="form-group">
#php
$label = 'Nome';
$field = 'nome';
#endphp
{!! Form::label($field, $label, ['class' => 'required']) !!}
{!! Form::text($field, old($field) ? old($field) : $profile->$field, ['class' => 'form-control', 'required']) !!}
</div>
<div class="clearfix"></div>
<div class="form-group">
#php
$label = 'Cognome';
$field = 'cognome';
#endphp
{!! Form::label($field, $label, ['class' => 'required']) !!}
{!! Form::text($field, old($field) ? old($field) : $profile->$field, ['class' => 'form-control', 'required']) !!}
</div>
<div class="clearfix"></div>
<div class="form-group">
#php
$label = 'Sex';
$field = 'sesso';
#endphp
{!! Form::label($field, $label, ['class' => 'required']) !!}
{!! Form::select($field, array('M' => 'Male', 'F' => 'Female'), old($field) ? old($field) : $profile->$field, ['class' => 'form-control', 'required']) !!}
</div>
<div class="clearfix"></div>
<div class="box-footer">
#php
$field = 'id';
$label = '<span class="ladda-label"><i class="fa fa-save"></i>'.trans('backpack::base.save').'</span>';
#endphp
{!! Form::hidden($field, old($field) ? old($field) : $profile->$field) !!}
{!! Form::button($label, ['class' => 'btn btn-success', 'type' => 'submit']) !!}
<span class="ladda-label">{{ trans('backpack::base.cancel') }}</span>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
What I expected to happen:
I expect that the form is validated
What happened:
when I submit, the request returns to me empty
What I've already tried to fix it:
Backpack, Laravel, PHP, DB version:
Laravel Framework 5.7.12
"php": "^7.1.3"
"backpack/backupmanager": "^1.4"
"backpack/crud": "^3.4"
"backpack/langfilemanager": "^1.0"
"backpack/logmanager": "^2.3"
"backpack/newscrud": "^2.1"
"backpack/pagemanager": "^1.1"
"backpack/permissionmanager": "^3.12"
"backpack/settings": "^2.1"
"barryvdh/laravel-elfinder": "^0.4.1"
"fideloper/proxy": "^4.0"
"laravel/framework": "5.7.*",
"laravel/tinker": "^1.0",
"laravelcollective/html": "^5.7",
"mews/purifier": "^2.1",
"tymon/jwt-auth": "^0.5.12"
Do you told backpack to not setup auth routes so you can setup your own ?
Go ahead to config/backpack/base.php and change setup_auth_routes and setup_my_account_routes accordingly.
If you have your routes cached don't forget about php artisan route:cache
Best,
Pedro

(1/1) ReflectionException Error Class App\Http\Request\UpdateApplicantRequest does not exist

I am new to laravel and I am trying to update to profile of the user who logged in. The error says:
Class App\Http\Request\UpdateApplicantRequest does not exist
But I imported it in the top of my controller.
HomeController.php
<?php
namespace App\Http\Controllers\Applicant;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\ApplicantsRepository;
use Flash;
use Response;
use App\Models\Applicant;
use App\Http\Request\UpdateApplicantRequest;
class HomeController extends Controller
{
private $applicantRepository;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(ApplicantsRepository $applicantRepo)
{
$this->middleware('applicant');
$this->applicantsRepository = $applicantRepo;
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('applicant-dashboard.home');
}
public function edit($id)
{
//$applicant = $this->applicantRepository->findWithoutFail($id);
$applicant = Applicant::where('id',$id)->get()->last();
if (empty($applicant)) {
Flash::error('Applicant');
return redirect(route('applicant.home'));
}
return view('applicant-dashboard.edit')->with('applicant', $applicant);
}
public function update($id, UpdateApplicantRequest $request)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant not found');
return redirect(route('applicant.home'));
}
$input = $request->all();
$applicant = $this->applicantRepository->update([
'name' => $input['name'],
'email' => $input['email'],
'password' => bcrypt($input['password']),
'address' => $input['address'],
'cellphone_no' => $input['cellphone_no']], $id);
Flash::success('Profile updated successfully.');
return redirect(route('applicant.home'));
}
}
Here is the code in my routes:
Route::get('/edit/{id}', 'HomeController#edit')->name('applicant.edit');
Route::patch('/put', 'HomeController#update')->name('applicant.update');
and the code in my blade file:
#section('content')
<section class="content-header">
<h1>
Applicant Profile
</h1>
</section>
<div class="content">
{{-- #include('adminlte-templates::common.errors') --}}
<div class="box box-primary">
<div class="box-body">
<div class="row" style="padding-left: 20px">
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
I am looking for help.
Thanks in Advance.
Firstly, you use wrong namespace of UpdateApplicantRequest.
Change:
use App\Http\Request\UpdateApplicantRequest;
To:
use App\Http\Requests\UpdateApplicantRequest;
Then, change your form from:
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
to:
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'post']) !!}
{!! method_field('patch') !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}

Laravel redirects to correct page but displays wrong url

Upon clicking the login button, the home page opens, which is right but in the url it displays /handleLogin instead of /home
Also, when i log out, the login page reopens which is right but in the url it displays /logout when the login page is actually open.
Why is this happening?
LoginController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
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.
|
*/
/* Login function*/
public function login(){
return view('login');
}
/* handleLogin function to request the data*/
public function handleLogin(Request $request){
$data = $request-> only('email', 'password');
if(\Auth::attempt($data)){
return redirect()-> intended('home');
}
return back()->withInput();
}
public function logout(){
\Auth::logout();
return redirect()->route('login');
}
}
Routes.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function() {
return view('welcome');
//return 'Hello. This is Laravel.';
});
Route::get('aboutus', function() {
return view('AboutUs');
//return 'Hello. This is Laravel.';
});
//Route::group(['middleware' => ['web']], function() {
Route::get('/login', ['as' => 'login', 'uses' => 'LoginController#login']);
Route::post('/handleLogin', ['as' => 'handleLogin', 'uses' => 'LoginController#handleLogin']);
Route::get('/home', ['as' => 'home', 'uses' => 'UsersController#home']);
Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginController#logout']);
//});
master.blade.php
<div data-role="navbar">
<ul>
#if(\Auth::check())
<li>
{{ link_to_route('logout', "Logout")}}
</li>
#else
<li>
{{ link_to_route('login', "Login")}}
</li>
#endif
</ul>
</div>
The form blade.
{!! Form::open(array('route' => 'handleLogin')) !!}
<div class="form-group">
{!! Form::label('email') !!}
{!! Form::text('email', null, array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('password') !!}
{!! Form::password('password', array('class' => 'form-control')) !!}
</div>
{!! Form::token() !!}
{!! Form::submit('Login', array('class' => 'btn btn-default')) !!}
{!! Form::close() !!}

Authenticate user Laravel

hi guys i have an simple application with laravel and i try to add a user Authentication to my app , this is my route.php file :
Route::model('task', 'Task');
Route::get('/login', 'HomeController#ShowLogin');
Route::post('/login', 'HomeController#doLogin');
Route::get('/logout' , 'HomeController#doLogout');
Route::group(array('before'=>'auth'), function(){
Route::get('/', 'TasksController#home');
Route::get('/create', 'TasksController#create');
Route::get('/edit/{task}', 'TasksController#edit');
Route::post('/edit', 'TasksController#doEdit');
Route::post('/create' , 'TasksController#saveCreate');
Route::get('/delete/{task}' , 'TasksController#delete');
Route::post('/delete', 'TasksController#doDelete');
Route::get('/task/{id}' , 'TasksController#show')->where('id', '\d+');
});
this is my HomeController.php ;
class HomeController extends BaseController {
public function showLogin()
{
return View::make('login');
}
public function doLogin()
{
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
dd(Auth::attempt($userdata));
if(Auth::attempt($userdata))
{
return Redirect::to('/');
}
else
{
return Redirect::to('login');
}
}
public function doLogout()
{
Auth::logout();
return Redirect::to('login');
}
}
and this is my login.blade.php file :
#extends('layout')
#section('content')
<section class="header section-padding">
<div class="background"> </div>
<div class="container">
<div class="header-text">
<h1>Learning Laravel: The Easiest Way</h1>
<p>
Showing a single task <br/> using route parameter!
</p>
</div>
</div>
</section>
<div class="container">
<section class="section-padding">
<div class="jumbotron text-center">
<h1>
Login
</h1>
<P>
{{ $errors->first('username') }}
{{ $errors->first('password') }}
</P>
{{ Form::open(['url' => '/login', 'class' => 'form']) }}
<div class="form-group">
{{ Form ::label('username', 'Username:') }}
{{ Form::text('username')}}
</div>
<div class="form-group">
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</div>
<div class="form-group">
{{ Form::submit('Login', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
</div>
</section>
</div>
#stop
when i input any username and password i got no error and i never login , and i redirect to login page and dd() always return bool(false), can any one help that , and explain more about Authentication in Laravel , Thank U :)
Edit
and this is my model/User.php and i dont add any code to this :
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
i create my user table manually
Auth::attempt($userdata) method will hash the password in $userdata array and check that hashed password with the database value,
so you need hashed passwords in the database,
to verify that,
please change the password in the database to $2y$10$3S3yDwfkwwLghedu4AoaTe//61QTaNC0ycTdp8hLfHtQS4XrgBPQy , and use a for the password field in the form
$2y$10$3S3yDwfkwwLghedu4AoaTe//61QTaNC0ycTdp8hLfHtQS4XrgBPQy is the laravel hashed password for a.

Categories