cant login with Auth::attempt - mysql

RegisterController :
public function register(Request $request)
{
$user=$request->file('cover');
$destination ='img/user';
$filename=$user->getClientOriginalName();
storage::put('img/user/'.$filename,file_get_contents($request->file('cover')->getRealPath()));
$user = new User();
$user->username = $request->username;
$user->email = $request->email;
$user->name = $request->name;
$user->password = bcrypt($request->password);
$user->cover = $filename;
$roles_id = DB::table('roles')->select('id')->where('rolename','admin')->first()->id;
$user->roles_id = $roles_id;
$user->save();
}
Login.blade.php :
<form action="/login" method="POST">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}">
<div class="row">
<div class="input-field col s6">
<input type="text" class="validate" name="username" placeholder="username">
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input type="password" class="validate" name="password" placeholder="Password">
</div>
</div>
<div class="row">
<div class="input-field col s5">
<input type="submit" class="btn">
</div>
</div>
</form>
LoginController :
public function postlogin(Request $request)
{
if(Auth::attempt([
'username' => $request->username,
'password' => $request->password
])){
return 'Cool';
}else{
return 'Not Cool';
}
}
just in case if you wanna see the route :
Route::get('/register','Auth\RegisterController#showRegistrationForm');
Route::post('/register', 'Auth\RegisterController#register');
Route::get('/login', 'Auth\LoginController#showLoginForm');
Route::post('/login', 'Auth\LoginController#postlogin');
i do read this post Laravel Auth::attempt() always false? but still dont know how to fix it
i try put
'password' => Hash::make($request->password)
and still got 'Not Cool'
:(

Laravel's Hash::make() uses bcrypt internally to hash the passwords.
But Hash::make() will generate different hash each time. So you can't use Hash::make() again on the same password and compare the two values. It will always return false as the hash generated each time would be different. However Laravel provides a Hash::check() to check the passwords hashed using Hash::make() or bcrypt() helper function.
If you want to verify the password hashed by using Hash::make() or bcrypt() helper function then you can do so by
/* Say you are using word secret as password while registering */
$password = 'secret';
$hashedPassword = Hash::make('secret');
/* Or */
$hashedPassword = bcrypt('sectet');
/* To verify the $hashedPassword - probably stored in a database */
function verify_password($password)
{
if(Hash::check($password, $hashedPassword)
{
echo "Passwords Match!";
}
else
{
echo "Passwords do not match :(";
}
}
/* While logging back (after registering)
in the first attempt you have a typo in your password secrets instead of secret
*/
$attempt1 = 'secrets';
verify_password($attempt1); /* will echo Passwords do not match :( */
/* in the second attempt you use the correct password secret */
$attempt2 = 'secret';
verify_password($attempt2); /* will echo Passwords Match! */
Hope this helps to understand.

Related

Upload multiple forms no save in mysql database laravel 9

could someone help me to find the error? only the post_image input is saved the others are not saved in the database what am I doing wrong?
I've checked it several times but only the filename of the post_image field is saved in the database, the other files are not persisting in the database, could someone help me where I'm going wrong?
Every help is welcome.
Thank you very much in advance.
create.blade.php
div class="form-group row">
<label for="post_image" class="col-md-4 col-form-label text-md-right">{{ __('Image') }}</label>
<div class="col-md-6">
<input type="file" name="post_image"/>
#error('post_image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_video" class="col-md-4 col-form-label text-md-right">{{ __('Video') }}</label>
<div class="col-md-6">
<input type="file" name="post_video"/>
#error('post_video')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_gif" class="col-md-4 col-form-label text-md-right">{{ __('GIF') }}</label>
<div class="col-md-6">
<input type="file" name="post_gif"/>
#error('post_gif')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
</div>
function store in controller -->
public function store(Request $request, Community $community)
{
$user = Auth::user();
$creds = $request->validate([
'post_image' => '|image|mimes:jpeg,jpg,png,svg|max:18048',
'post_video' => 'mimes:mp4,ogx,oga,ogv,ogg,webm|max:180048',
'post_gif' => '|image|mimes:gif|max:18048',
'title' => ['required'],
'post_text' => ['required'],
'post_url' => ['required']
]);
//IMAGE JPG,PNG,SVG
if ($image = $request->file('post_image')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['post_image'] = "$profileImage";
}
//END IMAGE JPG,PNG,SVG
//VIDEO MP4
if ($image = $request->file('post_video')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputmp4 ['post_video'] = "$profileImage";
}
//END VIDEOS
// GIF IMAGES
if ($image = $request->file('post_gif')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputgif ['post_gif'] = "$profileImage";
}
//END GIF IMAGES
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'] ?? '',
'post_video' => $inputmp4['post_video'] ?? '',
'post_gif' => $inputgif['post_gif'] ?? '',
]);
return redirect()->route('communities.show', $community);
}
Is it possible post_video and post_gif are empty? Php has a max_upload and max post size limit that is defined on the ini file. It is possible that that size is being exceeded. Hence your files are not actually uploading.
Also, your if statements are kinda confusing. Check this out :
//This if statement will always return true. Since you're assigning $image variable to $request->file('post_video').
if ($image = $request->file('post_video')) {
//Code For saving file
//Don't use this
}
// Instead you should use hasFile to check if the file is uploaded. here's how
if ($request->hasFile('post_video')) {
$video = $request->file('post_video');
//Code For saving file
//Use This instead
}
Also, at the last line, where you call create() method, do this:
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'], // skip the "?? ''" part
'post_video' => $inputmp4['post_video'],
'post_gif' => $inputgif['post_gif'],
]);
Now, if either post_image, post_video or post_gif is empty, you'll get a error and can see if the data is wrong.
Also, on a kinda related note, did you know laravel has a good helper to save files in storage? Check it out

How can I store an image to the database from modal?

I want to store an Image through a modal, usually, I store images this way. But it never stores, it stores null on the database, like the file wasn't even uploaded. Everything else on the modal stores perfectly, except the image.
This is the code for the image on my controller.
if($request->hasFile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time() .'.'.$extension;
$file->move('uploads/event/',$filename);
$event->image = $filename;
}
In my view, this is how I upload the image.
<div class="text-center">
<img src='http://ssl.gstatic.com/accounts/ui/avatar_2x.png' width="300px" height="300px" class="avatar img-circle img-thumbnail" alt="avatar" name="image" >
</div><hr>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="image" >
<label class="custom-file-label">Upload picture</label>
</div>
</div>
For the code I had, the only problem was that I didn't use the enctype="multipart/form-data". After looking for options, I found this and wrote it on the form of action and form-group div. It worked, the image stores and it also updates.
<form action="{{action('CalendarController#store')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="modal-body">
<div class="form-group" enctype="multipart/form-data">
Since I got this working I will start implementing other codes for better performance and start to learn about the Storage in laravel. Thanks to all of you!
Try this on your Controller:
use Image;
public function store(CreateRequest $request)
{
$file = $request->file('image');
$imagename = $file->getClientOriginalName();
$imageext = $file->getClientOriginalExtension();
$path = 'upload/image/'.time().'.'.$imageext;
$image = Image::make($file);
$image->save($path);
$input = $request->all();
$input['image'] = $path;
$user = $this->userRepository->create($input);
return redirect(route('users.index'));
}
do the same with update() function
The file will store in /public/upload/image folder
You can also try and use the 'Intervention\Image' and File class:
composer require intervention/image
<?php
...
use File;
use Intervention\Image\Facades\Image
...
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'image.'.$image->getClientOriginalExtension();
$save_path = storage_path().'uploads/event/';
$path = $save_path.$filename;
$public_path = 'uploads/event/'.$filename;
// Make the user a folder and set permissions
File::makeDirectory($save_path, $mode = 0755, true, true);
// Save the file to the server
Image::make($image)->resize(300, 300)->save($save_path.$filename);
// Save the public image path
$event->image = $public_path;
$event->save();
}
return response()->json(['path' => $path], 200);
} else {
return response()->json(false, 200);
}

Get difference number of two dates and subtract it from table laravel HR

So I'm trying to figure out how to make this work I have a Leave Application(which is currently just a form that stores the data) which is supposed to remove the "Days Granted" like Annual Leaves or Sick Leaves based on the dates from them for example "from 27/08/2020" and "to 30/08/2020" which is 3 days I want to get those numbers from between the dates and in the user table on the leave_days_granted field(which always has default value 20) to remove it from there so leave_days_granted - 3 = 17 something like this so I can display it on the view how many that user has left
I have added this in the user model
class User
{
public function leaveBalance()
{
$daysUsed = $this->leaves->map->numberOfDays()->sum();
return $this->leave_days_granted - $daysUsed;
}
// You can also add a helper to make your controller more readable.
public function hasAvailableLeave()
{
return $this->leaveBalance() > 0;
}
public function leaves()
{
return $this->hasMany(\App\Leave::class);
}
}
And this is added in the Leave Model
class Leave
{
protected $dates = ['from', 'to'];
public function numberOfDays()
{
return $this->from->diffInDays($to);
}
}
So here I don't get why this isn't working it's not changing anything in the database when I request a leave and I'm not sure now if I'm supposed to add something more on the Leave controller to call this or the View of the Leave
This is how I get the dates on the view
<div class="card-body">
<form method="POST" action="{{route('leaves.store')}}">
#csrf
<div class="form-group">
<label>From Date</label>
<div class="col-md-6">
<input class="datepicker" type="text" class="form-control #error('from') is-invalid #enderror" name="from" required="">
#error('from')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label>To Date</label>
<div class="col-md-6">
<input class="datepicker1" type="text" class="form-control #error('to') is-invalid #enderror" name="to" required="">
This is the form link This is the users table link This is the leaves table link
This is the LeaveController
public function index()
{
if(Auth::guard('admin')->check())
{
$users = User::all();
$leaves = Leave::latest()->paginate(5);
return view('admin/leave/index', compact('leaves'),compact('users'));
}
$role = Auth::guard('web')->user()->role_id;
if($role == 1)
{
return view('unauthorized');
}
else
{
$leaves = Leave::latest()->paginate(5);
return view('admin/leave/index', compact('leaves'));
}
}
public function create()
{
$leaves = Leave::latest()->where('user_id',auth()->user()->id)->paginate(5);
return view('leave.create',compact('leaves'));
}
public function store(Request $request)
{
$this->validate($request,[
'from'=>'required',
'to'=>'required',
'description'=>'required',
'type'=>'required'
]);
$data=$request->all();
$data['user_id']=auth()->user()->id;
$data['message']='';
$data['status']=0;
$leave =Leave::create($data);
$admins = Admin::all();
$users = User::where('role_id', 2)->get();
foreach ($admins as $admins) {
foreach($users as $users){
$admins->notify(new LeaveSent($leave));
$users->notify((new LeaveSent($leave)));
}
}
return redirect()->back()->with('message','Leave Created');
}
I understand that you have one user with 20 days availables for vacations or permissions.
You need that for each leave request, this count days of leave, and deduct of days availables for each user
I make this:
transform dates in object Carbon
get diff days
update days availables for user
In your controller
//transform dates in object Carbon
$from = Carbon::parse($request->from);
$to = Carbon::parse($request->to);
//get diff days
$diff = $from->diffInDays($to)
//find user and deduct days
$user = User::findOrFail(Auth::user()->id);
$user->days_availables = $user->days_availables - $diff
$user->update();
you learn more use Carbon library in: https://carbon.nesbot.com/docs/

How to make Razor not display special characters as html

The page I'm working on displays content from a database in readonly input box. My problem is that it's displaying any special characters as the html code (ie: & displays as &). How do you get the code to display properly?
I'm using QuerySingle to connect to the database, don't know if that makes a difference. I'm new to using Razor. Any help is much appreciated.
Code in question:
var queryloan = "SELECT * FROM loans WHERE LoanId = #0";
var queryloandata = db.QuerySingle(queryloan, queryformstatus_submitted.doc_loanid);
<form class="jotform-form" action="submit-form.cshtml?isadmin=#(isadmin)&loanid=#(loanid)" method="post" name="form_30905105572145" id="30905105572145" accept-charset="utf-8">
<input type="hidden" name="formID" value="30905105572145" />
<input type="hidden" name="doc_id" value="#doc_id" />
<div class="form-all">
<ul class="form-section">
<li id="cid_3" class="form-input-wide">
<div class="form-header-group">
<h2 id="header_3" class="form-header">
Borrower Sources & Uses Summary
</h2>
#if (queryformstatus_submitted.doc_approval == "Pending Approval" || queryformstatus_submitted.doc_approval == "Approved")
{
<text><br />
<br />
<div class="error">
This form has already been submitted and cannot be edited. It is for reference only.</div></text>
}
#if(userid != queryformstatus_submitted.doc_userid){
<text><br/><br/><div class="error">You may not edit this form. It is for reference only.</div></text>
}
</div>
</li>
<li class="form-line" id="id_4">
<label class="form-label-left" id="label_4" for="input_4">
1. Property Name:
</label>
<div id="cid_4" class="form-input">
<input type="text" class=" form-textbox" id="input_4" name="q4_1Property" size="40" value="#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)"/>
</div>
</li>
I'm not sure but I believe it may be something in this helper function that's causing the html code:
#helper checkEmptyPreFill(IEnumerable<dynamic> queryinputvalue, string field_id, string defaultval, int cloned = 0) {
var reqValue = queryinputvalue.FirstOrDefault(r => r.field_name.Equals(field_id));
var return_value = "";
if(reqValue != null){
return_value = reqValue.field_data;
} else {
return_value = defaultval;
}
if(cloned == 1){
return_value = "";
}
#return_value
}
The razor helper returns a HelperResult object so you'll have to convert it to a string before you can call HtmlDecode on it. Replace:
#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)
with the following:
#HttpUtility.HtmlDecode(Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName).ToString())
I would also suggest that you move some of the logic and data access code out of your view and into a controller but this should give you the result that you'e after.

Why are my inputs not resetting?

The below code generates several forms depending on data returned from the server. Everything generates fine, but after clicking on an AnswerOpenQuestion button the input does not clear/reset. What's going on here?
angularJs code:
var availableInterviewController = function($scope, $http) {
// define initial model
$scope.interviews = [];
// retrieve available interviews
$http.get('/api/UserInterviewsApi/AvailableInterviews')
.success(function(data) {
// update interviews
$scope.interviews = [];
$scope.interviews = data;
});
// define open question answer selection
$scope.Answer = "";
// define multiple choice selection
$scope.selectedChoice = "";
// define answer open question button
$scope.AnswerOpenQuestion = function() {
$scope.Answer = ans;
alert(q.Question + ' and ' + $scope.Answer);
$scope.Answer = ''; // <---This is not clearing/resetting the HTML form inputs
};
// define answer multiple choice button
$scope.AnswerMultipleChoice = function() {
//
};
};
// assign the new controller to the main angular app
myAngApp.controller('availableInterviewCtrl', availableInterviewController);
Html code:
<form class="form-group" ng-repeat="q in inter.Questions">
<fieldset style="display: inline-block;">
<legend>Question {{$index + 1}}</legend>
<!--Open Ended-->
<div class="form-group" ng-show="q.MultipleChoices.length === 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong><br />
</label>
<input name="openQuestion" id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="Answer" />
<button ng-click="AnswerOpenQuestion()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
<!--Multiple Choice Question-->
<div class="form-group" ng-show="q.MultipleChoices.length > 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong>
</label>
<div>
Select an answer:
<label ng-repeat="x in q.MultipleChoices">
<input name="currentChoice" type="radio" value="{{x.Id}}"
ng-model="selectedChoice" />
{{x.Choice}}
</label>
<button ng-click="AnswerMultipleChoice()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
</div>
</fieldset>
</form>
UPDATE - Solution
AngularJs:
// define open question answer selection
$scope.OpenAnswer = { Answer: '' };
// define answer open question button
$scope.AnswerOpenQuestion = function (q, ans) {
$scope.OpenAnswer.Answer = ans;
alert(q.Question + ' and ' + $scope.OpenAnswer.Answer);
// clear the input
$scope.OpenAnswer.Answer = '';
};
Html:
<input id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="OpenAnswer.Answer" />
Don't use the scope as a model instead make an object that wraps the data model and assign it to a property of the scope.
$scope.myModel = {Answer:''}
Also don't use value in most cases ngmodel is all you need for two way binding.
In js strings are immutable so the original reference is not being updated instead a new string is being made, the digest cycle won't see this as a change to the original string.