Laravel Auth attempt not working - laravel

First i created the Admin model in which i implemented it using Authenticable Admin.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
class Admin extends Model implements \Illuminate\Contracts\Auth\Authenticatable
{
//
use Authenticatable;
}
then i created the migration :
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->rememberToken();
$table->string('email');
$table->string('password');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('admins');
}
}
Replaced the Users model in config/auth.php with Admin Model :
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
AdminController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Auth;
class AdminController extends Controller{
public function getIndex()
{
$posts= Post::orderBy('created_at','desc')->take(3)->get();
return view('backend.index')->with(['posts'=>$posts]);
}
public function getLogin(){
return view('backend.login');
}
public function postLogin(Request $request){
$this->validate($request,[
'email'=>'required|email',
'password'=>'required'
]);
dd(Auth::attempt(['email'=>$request['email'],'password'=>$request['password']]));
if(!Auth::attempt(['email'=>$request['email'],'password'=>$request['password']])){
return redirect()->back()->with(['fail'=>'Could Not Log You In']);
}
return redirect()->route('admin.index');
}
public function getLogout(){
Auth::logout();
return redirect()->route('blog.index');
}
}
web.php
Route::get('/admin/login',[
'uses'=>'AdminController#getLogin',
'as'=>'admin.login'
]);
Route::post('/admin/login',[
'uses'=>'AdminController#postLogin',
'as'=>'admin.login'
]);
login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Admin Area</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{URL::to('css/bootstrap.min.css')}}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="{{URL::to('js/bootstrap.min.js')}}"></script>
#yield('styles')
</head>
<body>
<div class="container">
<div class="container-fluid">
#include('includes.info-box')
<form method="post" action="{{route('admin.login')}}">
<div class="form-group">
<label for="email">Email: </label>
<input type="email" class="form-control" id="email" name="email"
{{$errors->has('email')?'class=alert alert-danger':'' }}
value="{{Request::old('email')}}">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" class="form-control" id="password" name="password"
{{$errors->has('password')?'class=alert alert-danger':'' }}
>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Login</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</div>
</form>
</div>
</div>
</body>
</html>
so when i tried to login and dd the Auth Attempt it is returning false i have a user with email test#123.com and password test :
created the user using seeder :
<?php
use Illuminate\Database\Seeder;
class AdminTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
$admin = new \App\Admin;
$admin->email='test#123.com';
$admin->password='test#123.com';
$admin->save();
}
}

So for your seeder.
$admin = new \App\Admin;
$admin->email='test#123.com';
$admin->password='test#123.com';
$admin->save();
the password should be hashed using bcrypt.
$admin->password = bcrypt('test#123.com');
but as you've said, you're trying 'test' as the password, so it should be:
$admin->password = bcrypt('test');
that should work.
the reason is, Auth::attempt hashes the entered password using bcrypt.
So if the stored password in your database is not bcrypt-ed, Auth::attempt
will fail to match the two passwords.
For example you put test as the password, plain text, if you try to login to laravel using Auth::attempt using password = 'test', string 'test' will be compared against the bcrpyt version of 'test'.

Related

updateOrCreate - Laravel 8

I just started learning Laravel. I can't figure out how to update the data in the table. There is a table:
I want to insert the entry: machine_name + number_of_shifts. At the same time, if there is a machine_name record, then the number_of_shifts value must be updated for this record. Or, if there is no record, then create a new machine_name + number_of_shifts.
As a result, the error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `machines` set `machine_name` = Станок 456, `machines`.`updated_at` = 2023-01-16 20:52:34 where `id` is null)
What did I prescribe wrong?????? HELP ME FIGURE IT OUT, please.
Controller Code StoreController:
<?php
namespace App\Http\Controllers\Machines;
use App\Http\Controllers\Controller;
use App\Models\Machine;
use Illuminate\Http\Request;
class StoreController extends Controller
{
public function __invoke(Request $request){
$data = request()->validate([
'machine_name' => '',
'number_of_shifts' => '',
]);
Machine::updateOrCreate(['number_of_shifts' => $request->input('number_of_shifts')], $data);
return redirect()->route('machine.index');
}
}
Code create.blade
#extends('layouts.main')
#section('title-block') Добавить станок #endsection
#section('content')
<div class="d-flex p-2">
<form action="{{ route('machine.store') }}" method="post">
#csrf
<div class="mb-3">
<label for="machine_name" class="form-label">Станок</label>
<input type="text" name="machine_name" class="form-control" id="machine_name" placeholder="Станок 1">
</div>
<div class="mb-3">
<label for="number_of_shifts" class="form-label">Количество смен</label>
<input type="text" name="number_of_shifts" class="form-control" id="number_of_shifts" placeholder="1">
</div>
<button type="submit" class="btn btn-dark">Добавить станок</button>
<a class="btn btn-dark" href="{{ route ('machine.index') }}" role="button">Назад</a>
</form>
</div>
#endsection
Migration Code:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('machines', function (Blueprint $table) {
$table->id('machine_id');
$table->string('machine_name', 255);
$table->bigInteger('number_of_shifts')->unsigned()->nullable()->default(0);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('machines');
}
};
If you have changed the primary key name then you most define in model like this.
protected $primaryKey = 'machine_id';
And this is the bad idea to change its primary key.

Laravel Import Excel into DB: ErrorException Undefined array key "name"

I am trying to use the Maatwebsite\Excel package to let users import a csv or excel file and it get imported into the DB.
I am new to laravel, so I am not quite sure how to troubleshoot this issue.
I keep getting the error:
ErrorException Undefined array key "FIRST"
http://127.0.0.1:8000/import-form
CSV Sample Data
FIRST,LAST,EMAIL,PHONE,DEPARTMENT,LOCATION
test name 1,teast last 1,test#mail.com,123-123-1231,test department,test location
Routes:
Route::post('/import-form', [ImportPatientController::class, 'importForm'])->name('import.file');
ImportPatientController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ImportPatientModel;
use Excel;
use App\Imports\PatientImport;
use App\Http\Controllers\Controller;
class ImportPatientController extends Controller
{
public function importUploadForm()
{
return view('import-form');
}
public function importForm(Request $request)
{
Excel::import(new PatientImport,$request->file2);
return "Record are imported successfully!";
}
}
PatientImport.php (Imports Folder)
<?php
namespace App\Imports;
use App\Models\ImportPatientModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class PatientImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new ImportPatientModel([
'firstName'=>$row['FIRST'],
'lastName' => $row['LAST'],
'email' => $row['EMAIL'],
'phone' => $row['PHONE'],
'department' => $row['DEPARTMENT'],
'location' => $row['LOCATION'],
]);
}
}
ImportPatientModel.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class ImportPatientModel extends Model
{
use HasFactory;
protected $table = "imported_patients";
protected $fillable = ['firstName', 'lastName', 'email', 'phone', 'department', 'location'];
}
import-form.blade.php
<form action="" method="post" enctype="multipart/form-data" action="{{route('import.file')}}">
<img class="flowhealthlogoform" src="{{ url('images/flowhealthlogo.png')}}" />
<h1> BACKUP LIS </h1>
<!-- CROSS Site Request Forgery Protection -->
#csrf
<div class="form-group">
<label>Upload Excel Sheet</label>
<input type="file" class="form-control {{ $errors->has('file') ? 'error' : '' }}" name="file2" id="file">
<!-- Error -->
#if ($errors->has('file'))
<div class="error">
{{ $errors->first('file') }}
</div>
#endif
</div>
<input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
</form>```
Array keys in PHP are case sensitive.
I think if you change $row['FIRST'] to $row['first'] the issue will be solved!

Laravel 5.2.45 - empty $errors variable in views

Problem:
The $errors variable is empty in the views. There's talk that this has been fixed in 5.2 so hopefully the problem is on my end.
Environment:
Mac OS X
Laravel 5.2.45
The Codez:
Routes.php
Route::get('/', 'AlleleController#index');
Route::get('/register', function () {
return view('auth.register');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/alleles', 'AlleleController#index');
Route::post('/allele', 'AlleleController#store');
Route::delete('/allele/{allele}', 'AlleleController#destroy');
AlleleController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Allele;
class AlleleController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
// All methods require authentication except index.
$this->middleware('auth', ['except' => ['index']]);
}
/**
* Root page.
*
* #return Response
*/
public function index() {
return view('welcome');
}
/**
* Create a new allele.
*
* #param Request $request
* #return Response
*/
public function store(Request $request) {
$allele = new Allele();
// Get all input as an array.
$input = $request->all();
// Validate input.
if ($allele->validate($input)) {
// Valid input. Write to database.
// The inserted model instance is returned.
$result = $allele::create($input);
if ($result) {
// Insert successful.
$message = array('message' => 'Data added!');
return view('home', $message);
} else {
// Insert failed. Send errors to view.
$errors = array('errors' => 'Error saving data.');
return view('home', $errors);
}
} else {
// Invalid input. Get errors.
$errors = $allele->errors();
// Send errors to view.
return view('home', $errors);
}
}
}
?>
HomeController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index() {
return view('home');
}
}
Model: Allele.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Allele extends Validation {
/**
* The attributes that are mass assignable.
*/
protected $fillable = ['allele'];
/**
* Validation rules.
*/
protected $rules = array (
'allele' => 'required|max:20',
);
}
Model: Validation.php
<?php
namespace App;
use Validator;
use Illuminate\Database\Eloquent\Model;
class Validation extends Model {
protected $rules = array();
protected $errors;
public function validate($input) {
// Make a new validator object.
$v = Validator::make($input, $this->rules);
// Check for failure.
if ($v->fails()) {
// Set errors and return false.
$this->errors = $v->errors();
return false;
}
// Validation passed.
return true;
}
// Retrieves the errors object.
public function errors() {
return $this->errors;
}
}
View: views/common/errors.blade.php
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
View: views/home.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
You are logged in!
</div>
</div>
</div>
</div>
</div>
<!-- Create New Allele -->
<div class="panel-body">
<!-- Display Validation Errors -->
#include('common.errors')
<!-- New Allele Form -->
<form action="{{ url('allele') }}" method="POST" class="form-horizontal">
{{ csrf_field() }}
<!-- Allele Name -->
<div class="form-group">
<label for="allele-name" class="col-sm-3 control-label">Allele</label>
<div class="col-sm-6">
<input type="text" name="allele" id="allele-name" class="form-control">
</div>
</div>
<!-- Add Allele Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Add Allele
</button>
</div>
</div>
</form>
</div>
#endsection
All validation methods should be placed inside web middleware . I do not see any other error. Replace your route.php like this.
Route::group(['middleware' => ['web']], function ()
{
Route::get('/', 'AlleleController#index');
Route::get('/register', function () {
return view('auth.register');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/alleles', 'AlleleController#index');
Route::post('/allele', 'AlleleController#store');
Route::delete('/allele/{allele}', 'AlleleController#destroy');
});

Laravel simple form not setting errors and session variables

I am new to Laravel and I am trying to create a simple form that adds a record into a database table (that has 2 fields: ID and name).
Here is the code I have so far:
routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/banks/add', 'BanksController#add');
Route::post('/banks/add', 'BanksController#store');
});
BanksController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\BankFormRequest;
use App\Bank;
class BanksController extends Controller
{
public function add() {
return view('banks.add');
}
public function store(BankFormRequest $request) {
$bank = new Bank(array(
'name' => $request->get('name'),
));
$bank->save();
return redirect('/banks/add')->with('status', 'Your bank has been created! Its name is: '.$request->get('name'));
}
}
BankFormRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class BankFormRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|unique:banks|max:255',
];
}
}
Bank.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bank extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
}
banks/add.php
<form id="registerForm" role="form" method="post">
<pre><?=var_dump($errors)?></pre>
<pre>
<?php if (session()->has('status')): ?>
<?=session('status')?>
<?php endif; ?>
</pre>
<?php if (isset($errors) && $errors->any()): ?>
<?php foreach ($errors->all() as $error): ?>
<p class="alert alert-danger"><?=$erorr?></p>
<?php endforeach; ?>
<?php endif; ?>
<input type="hidden" name="_token" value="<?=csrf_token()?>">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Bank name" name="name">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
banks table
CREATE TABLE `banks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
In the banks/add view I have the form and 2 var_dumps of the $errors and session('status') variables, but they are always NULL. Otherwise, the form validator works well and it inserts my input into the database if it passes the rules I defined.
Anyone knows what causes my errors to not be shown?
in your banks/add.php
<p class="alert alert-danger"><?=$erorr?></p>
$erorr is wrong
If you are using laravel 5.2 try to remove web middleware on the route group this will fix your problem. why? because the RouteServiceProvider class will add it for you.
line 53 - 60 as of this writing.
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}

Flash data in Laravel 5

I'm trying to display flash data but it's not showing properly. It's showing:
{{ Session::get('flash_message') }}
but it should be the message
"Your article has been created"
What's wrong with my code? Thanks!
In my controller I have:
public function store(ArticleRequest $request)
{
Auth::user()->articles()->create($request->all());
\Session::flash('flash_message', 'Your article has been created');
return redirect('articles');
}
My app.blade.php is:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>App Name - #yield('title')</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ elixir('css/all.css') }}">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div class="container">
#if(Session::has('flash_message'))
<div class="alert alert-success">{{ Session::get('flash_message') }}</div>
#endif
#yield('content')
</div>
#yield('footer')
</body>
</html>
In my route.php I have the following: Curly braces display content as string not variables.
<?php
Blade::setContentTags('<%', '%>'); // for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>'); // for escaped data
Route::get('/', function() {
return 'Home Page';
});
Route::get('blade', function () {
return view('about');
});
Route::get('about', 'HelloWorld#about');
Route::get('foo', ['middleware' => 'manager', function() {
return 'this page may only be viewed by managers';
}]);
Route:resource('articles', 'ArticlesController');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
If you have this in your route.php:
Blade::setContentTags('<%', '%>');
then that means you cannot use curly brackets for blade content. Try this instead:
#if(Session::has('flash_message'))
<div class="alert alert-success">
<% Session::get('flash_message') %>
</div>
#endif
or simply remove the setContentTags() call from your route.php.
You can make a multiple messages and with different types.
Follow these steps below:
Create a file: "app/Components/FlashMessages.php"
namespace App\Components;
trait FlashMessages
{
protected static function message($level = 'info', $message = null)
{
if (session()->has('messages')) {
$messages = session()->pull('messages');
}
$messages[] = $message = ['level' => $level, 'message' => $message];
session()->flash('messages', $messages);
return $message;
}
protected static function messages()
{
return self::hasMessages() ? session()->pull('messages') : [];
}
protected static function hasMessages()
{
return session()->has('messages');
}
protected static function success($message)
{
return self::message('success', $message);
}
protected static function info($message)
{
return self::message('info', $message);
}
protected static function warning($message)
{
return self::message('warning', $message);
}
protected static function danger($message)
{
return self::message('danger', $message);
}
}
On your base controller "app/Http/Controllers/Controller.php".
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use App\Components\FlashMessages;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
use FlashMessages;
}
This will make the FlashMessages trait available to all controllers that extending this class.
Create a blade template for our messages: "views/partials/messages.blade.php"
#if (count($messages))
<div class="row">
<div class="col-md-12">
#foreach ($messages as $message)
<div class="alert alert-{{ $message['level'] }}">{!! $message['message'] !!}</div>
#endforeach
</div>
</div>
#endif
On "boot()" method of "app/Providers/AppServiceProvider.php":
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Components\FlashMessages;
class AppServiceProvider extends ServiceProvider
{
use FlashMessages;
public function boot()
{
view()->composer('partials.messages', function ($view) {
$messages = self::messages();
return $view->with('messages', $messages);
});
}
...
}
This will make the $messages variable available to "views/partials/message.blade.php" template whenever it is called.
On your template, include our messages template - "views/partials/messages.blade.php"
<div class="row">
<p>Page title goes here</p>
</div>
#include ('partials.messages')
<div class="row">
<div class="col-md-12">
Page content goes here
</div>
</div>
You only need to include the messages template wherever you want to display the messages on your page.
On your controller, you can simply do this to push flash messages:
use App\Components\FlashMessages;
class ProductsController {
use FlashMessages;
public function store(Request $request)
{
self::message('info', 'Just a plain message.');
self::message('success', 'Item has been added.');
self::message('warning', 'Service is currently under maintenance.');
self::message('danger', 'An unknown error occured.');
//or
self::info('Just a plain message.');
self::success('Item has been added.');
self::warning('Service is currently under maintenance.');
self::danger('An unknown error occured.');
}
...
Hope it'l help you.

Resources