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
Related
When I register a new user sign up, it save the password to database with hashed password. But when I go edit the user from the admin dashboard, the edit function work perfectly, but the password did not store or save as a hashed password, it save as plain text.
This is link to image show in database modification
This is the userController:
public function edit($id)
{
$user = $this->userRepository->find($id);
if (empty($user)) {
Flash::error('User not found');
return redirect(route('users.index'));
}
return view('users.edit')->with('user', $user);
}
/**
* Update the specified User in storage.
*
* #param int $id
* #param UpdateUserRequest $request
*
* #return Response
*/
public function update($id, UpdateUserRequest $request)
{
$user = $this->userRepository->find($id);
if (empty($user)) {
Flash::error('User not found');
return redirect(route('users.index'));
}
$user = $this->userRepository->update($request->all(), $id);
Flash::success('User updated successfully.');
return redirect(route('users.index'));
}
This is my fields.blade.php:
<!-- Name Field -->
<div class="form-group col-sm-6">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<!-- Email Field -->
<div class="form-group col-sm-6">
{!! Form::label('email', 'Email:') !!}
{!! Form::email('email', null, ['class' => 'form-control']) !!}
</div>
#push('scripts')
<script type="text/javascript">
$('#email_verified_at').datetimepicker({
format: 'YYYY-MM-DD HH:mm:ss',
useCurrent: true,
sideBySide: true
})
</script>
#endpush
<!-- Password Field -->
<div class="form-group col-sm-6">
{!! Form::label('password', 'Password:') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>
<!-- Role Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('role_id', 'Role Id:') !!}
{!! Form::number('role_id', null, ['class' => 'form-control']) !!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
Another thing: I'm using infyom Laravel generator.
This is the register controller (I make it by command make:auth):
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
This is the userRepository code:
<?php
namespace App\Repositories;
use App\Models\User;
use App\Repositories\BaseRepository;
/**
* Class UserRepository
* #package App\Repositories
* #version June 23, 2020, 3:11 pm UTC
*/
class UserRepository extends BaseRepository
{
/**
* #var array
*/
protected $fieldSearchable = [
'name',
'email',
'password',
'role_id'
];
/**
* Return searchable fields
*
* #return array
*/
public function getFieldsSearchable()
{
return $this->fieldSearchable;
}
/**
* Configure the Model
**/
public function model()
{
return User::class;
}
}
Add the update method to the UserRepository
protected function update(array $data,$id)
{
return User::where($id)->update([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
When trying to store an entry in my Database using Eloquent ORM i am getting the error,
Illuminate\Database\QueryException thrown with message "SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `animals` (`updated_at`, `created_at`) values (2019-04-25 22:35:47, 2019-04-25 22:35:47))"
However in my migrations i never specify name as being default as it is required.
My AnimalsController class.
public function create()
{
return view('animals.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$animal = Animal::create([
$request->input()
]);
// $animal = new Animal;
// $animal->name = $request->name;
// $animal->dob = $request->dob;
// $animal->description = $request->description;
// $animal->image = $request->image;
// $animal->available = $request->available;
//
// echo $request->id;
// echo "test";
// echo $animal->id;
// flash('Animal Added')->success();
return redirect()->route('animals.show')->with('animal', $animal);
}
/**
* Display the specified resource.
*
* #param \App\Animal $animal
* #return \Illuminate\Http\Response
*/
public function show(Animal $animal)
{
return view('animals.show')->with('animal', $animal);
}
Animal.php
class Animal extends Model
{
use SoftDeletes;
protected $dates = [
'created_at',
'updated_at'
];
/**
* Set the Attributes which are alllowed
* to be assigned
*/
protected $fillable = [
'name',
'dob',
'description',
'image',
'available'
];
create.blade.php - Where the form data is entered
<div class="row">
<div class="col">
{!! Form::open(['route' => 'animals.store'], ['class' => 'form', 'files' => true]) !!}
<div class="form-group">
{!! Form::label('name', 'Animal Name', ['class' => 'control-label']) !!}
{!! Form::text('name', null, ['class' => 'form-control input-lg', 'placeholder' => 'Waffles']) !!}
</div>
<div class="form-group">
{!! Form::label('dob', "DOB", ['class' => 'control-label']) !!}
{!! Form::date('dob') !!}
</div>
<div class="form-group">
{!! Form::label('description', "Description", ['class' => 'control-label']) !!}
{!! Form::textarea('description', null, ['size' => '20x3', 'class' => 'form-control input-lg', 'placeholder' => 'Describe the animal']) !!}
</div>
<div class="form-group">
{!! Form::label('image', "Image", ['class' => 'control-label']) !!}
{!! Form::file('image') !!}
</div>
<div class="form-group">
{!! Form::label('available', "Available", ['class' => 'control-label']) !!}
{!! Form::checkbox('available', 'value') !!}
</div>
<div class="form-group">
{!! Form::submit('Add Animal', ['class' => 'submit btn btn-info btn-lg', 'style' => 'width: 100%']) !!}
</div>
{!! Form::close() !!}
</div>
CreateAnimalsTable migration
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAnimalsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('animals', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 20);
$table->date('dob');
$table->mediumText('description');
$table->string('image');
$table->boolean('available')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('animals');
}
}
And in case it's worth anything my show.blade.php file.
<div class="container">
<div class="row">
<div class="col-xl-12 text-center">
<p class="text-primary" style="margin-top:100px;">{{ $animal->name }} has animal ID #{{ $animal->id }}. Date: {{ $animal->dob }}</p>
</div>
</div>
</div>
I have played around for hours trying to get this to work and i am painfully blind to the solution.
I should probably also mention that if i use this code
public function store(Request $request)
{
// $animal = Animal::create([
// $request->input()
// ]);
$animal = new Animal;
$animal->name = $request->name;
$animal->dob = $request->dob;
$animal->description = $request->description;
$animal->image = $request->image;
$animal->available = $request->available;
echo $request->id;
echo "test";
echo $animal->id;
// flash('Animal Added')->success();
return redirect()->route('animals.show')->with('animal', $animal);
}
I instead get this error.
Illuminate\Routing\Exceptions\UrlGenerationException thrown with message "Missing required parameters for [Route: animals.show] [URI: animals/{animal}]."
Which i have also had no use fixing, i am using a resource in the web.php file
Route::resource('animals', 'AnimalsController');
This led me to believe that $fillable was not working as intended and instead used the above method, however it still didn't work.
If i do make Name default in the Schema i will then have to give every other attribute a default value, which i don't want to do.
Hopefully i have given enough information to be of use, thank you :D
I found two issues in this.
First, I dont think this is gonna work
$animal = Animal::create([
$request->input()
]);
This is an array wrapped inside another array. Instead, lets write:
$animal = Animal::create($request->input());
Or:
$animal = Animal::create($request->all());
In the second example, I think an animal is created, but redirected route is not specified correctly:
return redirect()->route('animals.show')->with('animal', $animal);
Let's say:
return redirect()->route('animals.show', $animal->id);
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() !!}
I created a form to update the role model but on clicking on the save button, it does not appear to submit to the controller method. Even the validation errors message does not appear if the name input field is invalid. Below you can find the code used for the form.
Form:
{!! Form::model($role, ['route' => ['roles.update', $role->id], 'method' => 'put']) !!}
#include('roles.fields')
{!! Form::close() !!}
The fields for the form are:
<!-- Name Field -->
<div class="form-group col-sm-6">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<!-- Display Name Field -->
<div class="form-group col-sm-6">
{!! Form::label('display_name', 'Display Name:') !!}
{!! Form::text('display_name', null, ['class' => 'form-control']) !!}
</div>
<!-- Description Field -->
<div class="form-group col-sm-12 col-lg-12">
{!! Form::label('description', 'Description:') !!}
{!! Form::textarea('description', null, ['class' => 'form-control', 'rows' => '5']) !!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
Request:
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Models\Role;
class UpdateRoleRequest extends Request
{
/**
* 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 Role::$rules;
}
}
Controller:
/**
* Update the specified Role in storage.
*
* #param int $id
* #param UpdateRoleRequest $request
*
* #return Response
*/
public function update($id, UpdateRoleRequest $request)
{
$role = $this->roleRepository->findWithoutFail($id);
if (empty($role)) {
Flash::error('Role not found');
return redirect(route('roles.index'));
}
$role = $this->roleRepository->update($request->all(), $id);
Flash::success('Role updated successfully.');
return redirect(route('roles.index'));
}
Model:
<?php
namespace App\Models;
use Eloquent as Model;
use Zizaco\Entrust\EntrustRole;
use Illuminate\Database\Eloquent\SoftDeletes;
class Role extends EntrustRole
{
use SoftDeletes;
public $table = 'roles';
protected $dates = ['deleted_at'];
public $fillable = [
'name',
'display_name',
'description'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'name' => 'string',
'display_name' => 'string'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
'name' => 'required|unique:roles'
];
}
Please help if possible. Thanks!
You cant use put as the form method. Read the documentation about method spoofing in laravel
{!! Form::model($role, ['route' => ['roles.update', $role->id], 'method' => 'post']) !!}
<input type="hidden" name="_method" value="PUT">
#include('roles.fields')
{!! Form::close() !!}
For those people that work with HTML and laravel 5.2:
<form method="post" ... > {{ method_field('PUT') }} ... </form>
Hope this help people.
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.