Updating a row in the database from the modal using Laravel Eloquent - php

I have a calls table that is populated from a form,
calls table
public function up()
{
Schema::create('calls', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->timestamps();
$table->text('terminal_id', 20);
$table->text('terminal_name', 100);
$table->text('fault_description');
$table->string('call_status', 10)->default('New call');
$table->text('assigned_FE', 20)->nullable();
$table->text('closed_on', 20)->nullable();
$table->text('closed_by', 50)->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
I want to fetch and update only the assigned_FE column in my calls table with a user's entry on this modal form
<div class="modal-body">
<form action="{{route('Call.update')}}" method="POST" style="padding:30px 0px">
#csrf
<div class="col-md-6">
<div class="input-group" style="width: 100%;">
<label for="assigned_FE">{{ __('Name of field engineer') }}</label><br>
<input type="text" name="assigned_FE" id="assigned_FE" class="form-control" placeholder="Name of field engineer" style="padding: 20px;" required>
</div>
</div>
<button type="submit" class="btn-primary" style="padding: 10px; font-size: 14px; border: 0; margin-top:25px">{{ __('Submit') }}</button>
</form>
</div>
How do I achieve this without fetching all the data in a call's row?
I don't have an idea of what to place in my CallsController
This is my CallsController
public function edit($id)
{
//find the call in the db and save it as a variable
$call = Call::find($id);
//return it to the view and pass in the variable
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
and here is my Calls model (Call.php)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Call extends Model{
protected $fillable = [
'terminal_id',
'terminal_name',
'branch_address',
'fault_description'
];
//describing a one-to-many-relationship between calls and users
public function user(){
return $this->belongsTo('App\User');
}
}

Ok, first in your Model you should include all column name in the fillable array your Call model is missing assigned_FE
class Call extends Model{
protected $fillable = [
'terminal_id',
'terminal_name',
'branch_address',
'atm_variant',
'assigned_FE',
'closed_on',
'closed_by',
'fault_description'
];
//describing a one-to-many-relationship between calls and users
public function user(){
return $this->belongsTo('App\User');
}
after making sure that all columns are present in the fillable array, change your Form action to point to call.update route
<div class="modal-body">
<form action="{{route('call.update')}}" method="POST" style="padding:30px 0px">
#csrf
<div class="col-md-6">
<div class="input-group" style="width: 100%;">
<label for="assigned_FE">{{ __('Name of field engineer') }}</label><br>
<input type="text" name="assigned_FE" id="assigned_FE" class="form-control" placeholder="Name of field engineer" style="padding: 20px;" required>
</div>
</div>
<button type="submit" class="btn-primary" style="padding: 10px; font-size: 14px; border: 0; margin-top:25px">{{ __('Submit') }}</button>
</form>
your controller
use App\Call;
public function update(Request $request, $id)
{
$assigned_FE = $request->assigned_FE;
$call = Call::findOrFail($id);
$call->assigned_FE = $assigned_FE;
$call-save();
return redirect()->back();
}
your routes file should have something like this:
route::post('call/{id}', CallsController#update)->name('call.update);

Get the required record in the update function and then update it.
public function update(Request $request, $id)
{
$call = Call::find($id);
$input = $request->all();
$call->assigned_FE = $input['assigned_FE'];
$call->update();
// redirect wherever you want
return redirect()->back();
}

Here you go If I try to understand your question!
public function update(Request $request, $id)
{
if($request->isMethod('post')){
$data = $request->all();
//this part will get your item with that specific id updated just match database columns with form input names.
call::where(['id'=> $id])
->update(['terminal_name'=> $data['terminal_name'], 'fault_description' =>$data['fault_description']]);
//redirected to another page after updating or
//return back(); to stay on same page.
return redirect('/page');
}
}

Related

Laravel Error to inicialice ValidationFactory

I'm making my login system, through the LoginController controller, which in turn calls a request called loginRequest [I still have to update some names to Pascal]
My request only has two rules that username and password are required.
Then in a function getCredentials() I capture the username of this and validate that it is an email or not, this to give the user the option to log in both ways.
To identify if the user is actually an email, create a method 'isMail' in which I establish $factory with the content validated through an alias set to Validacion\Factory , ValidationFactory, but when executing the submit button it throws me the error :
Target [Illuminate\contracts\Validation\Factory] is not instantiable.
Could you help me?
template [login.blade.php]:
#extends('components\header')
<section class="vh-100">
<div class="container-fluid h-custom">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-4">
<img src="{{ URL::asset('img/logo.png') }}"
class="img-fluid" height="500">
</div>
<div class="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
<form action="{{route('samein.login')}}" method="POST">
#csrf
<!-- Email input -->
<div class="form-outline mb-4">
<input type="text" name="username" class="form-control form-control-lg"
placeholder="Usuario" />
<label class="form-label" for="form3Example3">Usuario</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="password" class="form-control form-control-lg"
placeholder="Contraseña" />
<label class="form-label" for="form3Example4">Contraseña</label>
</div>
<div class="text-rigth text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">Iniciar Sesión</button>
</div>
</form>
</div>
</div>
</div>
</section>
controller[LoginController.login]
<?php
namespace App\Http\Controllers;
use App\Http\Requests\loginrequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Queue\RedisQueue;
class LoginController extends Controller
{
public function index(){
return view('login');
}
public function login( loginrequest $request ){
$credentiales = $request->getCredentials();
if( Auth::validate($credentiales) ){
return redirect()->to('login')->withErrors('auth.failed');
}
$user = Auth::getProvider()->retrieveByCredentials($credentiales);
Auth::login($user);
return $this->authenticated($request,$user);
}
public function authenticated (Request $request,$user){
return redirect('accountModule.indexusers');
}
}
and my Request[loginrequst.php]
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\contracts\Validation\Factory as ValidationFactory;
class loginrequest 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<string, mixed>
*/
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
public function getCredentials(){
$username = $this->get('username');
if( $this->isMail($username) ){
return['email'=> $username,
'password' => $this->get('password')
];
}
return $this->only('username','password');
}
public function isMail($value){
$factory = $this->container->make(ValidationFactory::class);
return !$factory->make(['username'=>$value],['username'=>'email'])->fails();
}
}
I was reading your problem and I found interesting the way you plan to check if the email is there or not.
I know it doesn't answer your question but you could try the following:
In your Request:
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
In your controller:
public function login( loginrequest $request ){
$field = filter_var($request->input('username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('username')]);
//validate credentials
if (!Auth::validate($request->only($field, 'password'))) {
return redirect()->to('login')->withErrors('auth.failed');
}
//create a session
$user = Auth::getProvider()->retrieveByCredentials($request->only($field, 'password'));
Auth::login($user);
return redirect()->to('/');
}
don't forget to configure your web.php file, so that the routes work for you. I hope I've helped.

Laravel - Model attributes stay NULL in database after creation

I have a model named Articles which contained three attributes: 'title', 'subtitle' and 'body' and it worked perfectly but after adding four columns to that model ('subtitle2', 'body2', 'subtitle3' and 'body3') the newly added columns stay NULL after creating articles.
There is clearly something that I missed but I can't figure out what.
This is the migration:
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('subtitle2')->nullable()->default(null);
$table->text('body2')->nullable()->default(null);
$table->string('subtitle3')->nullable()->default(null);
$table->text('body3')->nullable()->default(null);
});
}
After migrating I edited my app/Http/Models/Article.php and it looks like this:
protected $fillable = [
'title',
'subtitle',
'body',
'subtitle2',
'body2',
'subtitle3',
'body3',
];
This is my app/Http/Livewire/CreateArticle.php
class CreateArticle extends Component
{
use WithFileUploads;
public $title;
public $subtitle;
public $body;
public $category;
public $subtitle2;
public $body2;
public $subtitle3;
public $body3;
public $temporary_images;
public $images = [];
public $article;
public function store()
{
$this->validate();
$this->article = Category::find($this->category)->articles()->create($this->validate());
$this->article->user()->associate(Auth::user());
$this->article->save();
if(count($this->images)){
foreach($this->images as $image){
$newImage = $this->article->images()->create(['path'=>$image->store('images', 'public')]);
dispatch(new ResizeImage($newImage->path, 600, 400));
}
}
}
And finally I added these lines to the form:
{{-- INSERT SUBTITLE 2 --}}
<div class="mb-3">
<label for="subtitle2" class="form-label">Second paragraph subtitle</label>
<input type="text" wire:model="subtitle2" class="form-control" id="subtitle2">
</div>
{{-- INSERT PARAGRAPH 2 --}}
<div class="mb-3">
<label for="body2" class="form-label">Second paragraph</label><br>
<textarea class="form-control" wire:model="body2" id="body2" cols="30" rows="3"></textarea>
</div>
{{-- INSERT SUBTITLE 3 --}}
<div class="mb-3">
<label for="subtitle3" class="form-label">Third paragraph subtitle</label>
<input type="text" wire:model="subtitle3" class="form-control" id="subtitle3">
</div>
{{-- INSERT PARAGRAPH 3 --}}
<div class="mb-3">
<label for="body3" class="form-label">Third paragraph</label><br>
<textarea class="form-control" wire:model="body3" id="body3" cols="30" rows="3"></textarea>
</div>
dd($this); is returning the following
Tinker is showing all columns
You need to specify
protected $rules
in order to use
$this->validate()
Assuming the dd(); image you provided is the latest. I can see the new columns does not exists in database. ('subtitle2', 'body2', 'subtitle3' and 'body3') all these are not available in list.
so I think you are missing to run the migrate command
php artisan migrate

How to fix 'The POST method is not supported for this route. Supported methods: GET, HEAD.'?

I'm trying to make a website where you can upload games and see them on the home page, but because I need a two-step form I can't directly send them to the database.
my controller:
public function createstep1(Request $request)
{
$naam = $request->session()->get('naam');
return view('games.game',compact('naam', $naam))->with('games', game::all());
}
public function postcreatestep1(Request $request)
{
$validatedData = $request->validate([
'naam' => 'required',
'geslacht' => 'required',
]);
if(empty($request->session()->get('naam'))){
return redirect('/game');
}else{
$naam = $request->session()->get('naam');
$naam->fill($validatedData);
$request->session()->put('naam', $naam);
}
return redirect('/newgame');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$naam = $request->session()->get('naam');
return view('games.newgame',compact('naam',$naam));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$game= new Game();
$game->game= $request['game'];
$game->naam= $request['naam'];
$game->geslacht= $request['geslacht'];
$game->save();
return redirect('/game');
}
<div id="newgame" style="height: 500px; width: 250px; float: left;">
<form method="post" name="naam">
#csrf
<input id="naam" name="naam" placeholder="naam">
<select name="geslacht" type="text">
<option name="man">man</option>
<option name="vrouw">vrouw</option>
</select>
<a type="submit"><button>volgende</button></a>
</form>
</div>
<div id="games" style="float: right">
#foreach($games as $game)
{{$game->game}} <br><br>
#endforeach
</div>
<h1>welkom {{$naam}}</h1>
<form method="post">
#csrf
<h3>game invoeren</h3>
<input type="text" id="gamenaam" name="gamenaam" placeholder="game">
<a id="submit" type="post" name="game" href="/newgame/store">
<button>verstuur</button></a>
</form>
Route::get('/', function () {
return view('welcome');
});
Route::get('/newgame', function () {
return view('games.newgame');
});
//Route::post('/newgames', ['as' => '/newgames', 'uses' => 'GameController#create']);
Route::get('/game', 'GameController#createstep1');
Route::post('/game', 'GameController#postcreatestep1');
Route::get('/newgame', 'GameController#create');
Route::post('/newgame/store', 'GameController#store');
I expect it will drop the game + name and gender in the database but the actual code gives an error message.
This work is for school but they can't help me if you have suggestions or can help me fix the problem that would be great.
When registering a new route you need to specify which HTTP method the route is for. Usually Route::get() is alright but since you're sending a POST request with your form to the controller method postcreatestep1, this one needs to be registered as a POST route with Route::post().
You may also declare a route available for multiple HTTP methods with the Route::match() method.
To get an overview of all available router methods the official documentation of Laravel is a good starting point.

Undefined variable:user laravel

I keep on getting this error whenever I try to enter the upload page.
Can anybody help?
I have already done the compact part to make sure that the variable is being passed to the view and also my route should be ok I think.
I tried using dd but all it does is keep on showing me the error
Error: Undefined variable: user (View: C:\xampp\htdocs\Evaluation\resources\views\upload.blade.php)
Here are my codes:
upload.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UploadController:
public function upload(){
return view(‘upload’);
}
public function store(Request $request,$id){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
var_dump('has file '.$request->hasFile('file'));
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
// $Image->user_id = $id;
//$Image->save();
$user->find($id);
dd($user);
$user->Images()->save($Image);
}
return redirect('/home');
}
public function test(){
$user = user_information::where('id')->get();
return view('upload', compact('user'));
}
Route: (this are my route)
Route::get('/UploadUser/upload','UploadController#upload’);
Route::post('/UploadUser','UploadController#store');
Route::post('/UploadUser/upload', 'UploadController#test');
Another question: I keep on getting this error when i try to upload a file, so what should I do?
Here is the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (form.images,
CONSTRAINT images_user_id_foreign FOREIGN KEY (user_id) REFERENCES
usere_information (id)) (SQL: insert into images (name,
size, user_id, updated_at, created_at) values (download.png,
4247, 1, 2017-10-25 08:54:57, 2017-10-25 08:54:57))
Image model:
class Image extends Model
{
protected $fillable = array('name','size','user_id');
public function user_informations() {
return $this->belongsTo('App\user_information', 'user_id', 'id');
}
}
Images table:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('size');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user_informations');
$table->timestamps();
});
User_information table:
Schema::create('user_informations', function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->binary('signature');
$table->String('Name');
$table->timestamps();
});
User_information model:
class user_information extends Eloquent
{
protected $fillable = array('signature', 'Name');
protected $table = 'user_informations';
protected $primaryKey = 'id';
public function Images() {
return $this->hasOne('App\Image','user_id');
}
}
How to get the image?
Here is the view folder:
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
Edit<br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endforeach
#if($data3->count())
#foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
#endif
#endforeach
HomeController:
public function getInfo($id) {
$data = user_information::where('id',$id)->get();
$data3=Image::where('user_id',$id)->get();
return view('test',compact('data','data3'));
Because you didn't pass the user to your upload view, try to pass it like this :
public function upload(){
$id = 1 //The wanted user or if the user is authenticated use Auth::id()
$user = User::find($id);
return view('upload')->withUser($user);
}
Or if the user is authenticated use Auth in the view :
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{auth()->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
For the second problem it's because in the route you have
Route::post('/UploadUser','UploadController#store');
and the your store method signature is
public function store(Request $request,$id){
The $id parameter that did the problem because it's not defined in the route so simply remove it from the method signatre
public function store(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id; // here id is declared no need for the parameter
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
$Image->user_id = $id;
$Image->save();
}
return redirect('/home');
}
For the third case you have to change the routes from :
Route::get('/UploadUser/upload','UploadController#upload’);
to
Route::get('/UploadUser/{user}/upload','UploadController#upload’)->name('user.upload.image');
And in the view add the id in the upload button url maybe like this :
{!! route('user.upload.image', ['user'=>$currentUser->id]) !!}
Then in the upload method :
public function upload(user_information $user){ // route model binding here
// dd($user); //for testing only :)
return view('upload')->withUser($user);
}
In the view change
<input type="hidden" name="user_id" value="{{auth()->id()}}">
To
<input type="hidden" name="user_id" value="{{$user->id()}}">
And you are good to go ;)
#foreach ($data as $currentUser)
<b>Name: </b>{{ $currentUser->Name }}<br><br>
Edit<br>
#if($currentUser->Image)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endif
<a href="{!! route('user.upload.image', ['id'=>$currentUser->id]) !!}">
#endforeach
You have miss to pass id in your where condition,
public function test(){
$user = user_information::where('id',$id)->first();
return view('create1', compact('user'));
}
and you have to pass your user data into this,
public function upload(){
$user = user_information::where('id',$id)->first();
return view(‘upload’,compact('user'));
}
Hope it helps,
On your upload function, you have to pass the user variable because you use the $user in the view. So the controller will be
public function upload() {
$user = Auth::user();
return view('upload', compact('user'));
}
do not forget to change the $user based on your need.
You have to pass an $id variable into your test() method. Then please comment below what's the error next so I can follow you through.
Update
Since you don't want to pass an id. You can use:
public function test(){
$u = Auth::user();
$user = user_information::where('id', $u->id)->get();
return view('upload', compact('user'));
}
OR
Try to use first() instead of get().
More option:
I have noticed, you're using the upload() method here, why not passing the $user there? like so:
public function upload(){
$user = Auth::user();
return view(‘upload’, compact('user'));
}

Laravel Auth::attempt failing each time

I have created a test user on my laravel app. The details are
user: joe#gmail.com pass: 123456
When I go through the registration process everything works as expected and an entry is made into the users table of the database
Once this is finished I redirect the user to the dashboard.
public function postCreate(){
//Rules
$rules = array(
'fname'=>'required|alpha|min:2',
'lname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()){
//Save in DB - Success
$user = new User;
$user->fname = Input::get('fname'); //Get the details of form
$user->lname = Input::get('lname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));//Encrypt the password
$user->save();
return Redirect::to('/books')->with('Thank you for Registering!');
}else{
//Display error - Failed
return Redirect::to('/')->with('message', 'The Following Errors occurred')->withErrors($validator)->withInput();
}
}
I then navigate back to the landing page and attempt to log in using the credentials above and I keep getting told that Auth::attempt() is failing hence my user cannot log into the application.
public function login(){
if(Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))){
//Login Success
echo "Success"; die();
return Redirect::to('/books');
}else{
//Login failed
echo "Fail"; die();
return Redirect::to('/')->with('message', 'Your username/password combination was incorrect')->withInput();
}
}
Does anyone know why this is happening? This is the Schema for my users table:
Schema::create('users', function($table){
$table->increments('id');
$table->integer('type')->unsigned();
$table->string('fname', 255);
$table->string('lname', 255);
$table->string('email')->unique();
$table->string('password', 60);
$table->string('school', 255);
$table->string('address_1', 255);
$table->string('address_2', 255);
$table->string('address_3', 255);
$table->string('address_4', 255);
$table->string('remember_token', 100);
$table->timestamps();
});
Any help is much appreciated.
'View for Login':
<div class="page-header">
<h1>Home page</h1>
</div>
<!-- Register Form -->
<form action="{{ action('UsersController#postCreate') }}" method="post" role="form">
<h2 class="form-signup-heading">Register</h2>
<!-- Display Errors -->
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<!-- First Name -->
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" name="fname" />
</div>
<!-- Last Name -->
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" name="lname" />
</div>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<!-- Confirm Password -->
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" name="password_confirmation" />
</div>
<input type="submit" value="Register" class="btn btn-primary"/>
</form>
<!-- Login Form -->
<form action="{{ action('UsersController#login') }}" method="post" role="form">
<h2 class="form-signup-heading">Login</h2>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<input type="submit" value="Login" class="btn btn-primary"/>
</form>
Can you run this function below - and tell me where the error occurs? It will diagnose the problem:
public function testLogin()
{
$user = new User;
$user->fname = 'joe';
$user->lname = 'joe';
$user->email = 'joe#gmail.com';
$user->password = Hash::make('123456');
if ( ! ($user->save()))
{
dd('user is not being saved to database properly - this is the problem');
}
if ( ! (Hash::check('123456', Hash::make('123456'))))
{
dd('hashing of password is not working correctly - this is the problem');
}
if ( ! (Auth::attempt(array('email' => 'joe#gmail.com', 'password' => '123456'))))
{
dd('storage of user password is not working correctly - this is the problem');
}
else
{
dd('everything is working when the correct data is supplied - so the problem is related to your forms and the data being passed to the function');
}
}
Edit: one thought - are you sure the user is being correctly saved in the database? Have you tried to 'empty/delete' your database and try your code again? In your current code, it will fail if you keep registering with joe#gmail.com - because it is unique. But you dont catch the error anywhere. So empty the database and try again...
Edit 2: I found another question you posted with the same problem - and in there you mentioned that the following code is your user model?
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function getAuthIdentifier() {
}
public function getAuthPassword() {
}
public function getRememberToken() {
}
public function getRememberTokenName() {
}
public function getReminderEmail() {
}
public function setRememberToken($value) {
}
}
Is that EXACTLY your current user model? Because if so - it is wrong - none of those functions should be blank.
This is what a CORRECT user model should look like for Laravel 4.2
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
You would make sure about:
your model:
mine looks like:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
public function getAuthIdentifier()
{
Return $this->getKey ();
}
public function getAuthPassword()
{
return $this->password;
}
}
make sure your app/config/auth.php is configured correctly
make sure app/config/app.php has service provider
'Illuminate\Auth\AuthServiceProvider',
Make sure your controller class has auth. before writing class you have used Auth (I mean include Auth class)
That all could make Auth doesn't work well
With password hashing enabled, the User model must override these methods:
public function getAuthIdentifierName()
{
return 'email';
}
public function getAuthIdentifier()
{
return request()->get('email');
}
public function getAuthPassword()
{
return Hash::make(request()->get('password'));
}
What is the value for strlen(Hash::make(Input::get('password')))? If it is greater than 60, then this would cause the authentication to fail each time, as the stored password is not the full hash.
Good day, here is what I discovered when I encountered the same error: A simple string compare will reveal that the two hashing methods produce two different hashed values.
echo strcmp(Hash::make('password'),bcrypt('password'));
My assumption is that Auth::attempt([]) uses bcrypt() to hash out passwords which produces a different value to what you used Hash:make().

Categories