Laravel 5.7 Auth::attempt return false - authentication

Auth::attempt always return false , can't understand why .
web.php
Route::post('/login','SessionsController#store');
Route::post('/register','RegisterController#store');
RegisterController.php
public function store()
{
$this->validate(\request(),[
'name' => 'bail|required|min:3|max:30|string',
'email' => 'bail|required|email',
'password' => 'required|confirmed'
]);
$user = User::create(request(['name','email','password']));
$user->fill([
'password' => Hash::make(\request()->newPassword)
])->save();
auth()->login($user);
return redirect()->home();
}
SessionsController.php
public function store(Request $request)
{
$credentials = $request->only('email', 'password');
if (! Auth::attempt($credentials)) {
return back()->withErrors(['message'=>'Email and Password doesn\'t match']);
}
return redirect()->home();
}
create.blade.php (Login Page)
<form action="/login" method="post">
#csrf
<div class="form-group">
<label for="email" class="form-text">Email :</label>
<input type="email" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password" class="form-text" >Password :</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<input type="submit" class="btn btn-primary float-right" value="Register">
</form>
Every thing is okay with registration and database , passwords is hashed .
Auth::attempt always return false .
Can't understand why , posted it after few hours of searching .. most of code is just copied from documentation.
Thanks in advance.

just changing
$user = User::create(request(['name','email','password']));
$user->fill([
'password' => Hash::make(\request()->newPassword)
])->save();
to
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => bcrypt(request('password'))
]);

Related

How to insert multiple text input data with checkbox in laravel?

Basically I want to insert into database the data according to input value. I have multiple checkbox and input field. When I store data only " A " then its working and others are null values. If I stored others with A then stored all the values. User can be check and input values any time and any number of check box.
Here are the code snippet,
<form action="">
<input type="checkbox" name="txt_check[]" id="">A
<label for="fname">Win1:</label>
<input type="text" id="fname" name="txt_win[]"><br><br>
<label for="fname">Win2:</label>
<input type="text" id="fname" name="txt_loss[]"><br><br>
<label for="fname">Win3:</label>
<input type="text" id="fname" name="txt_draw[]"><br><br>
<input type="checkbox" name="txt_check[]" id="">B
<label for="lname">Loss1:</label>
<input type="text" id="fname" name="txt_win[]"><br><br>
<label for="lname">Loss2:</label>
<input type="text" id="fname" name="txt_loss[]"><br><br>
<label for="lname">Loss3:</label>
<input type="text" id="fname" name="txt_draw[]"><br><br>
<input type="checkbox" name="txt_check[]" id="">C
<label for="lname">Draw1:</label>
<input type="text" id="fname" name="txt_win[]"><br><br>
<label for="lname">Draw2:</label>
<input type="text" id="fname" name="txt_loss[]"><br><br>
<label for="lname">Draw3:</label>
<input type="text" id="fname" name="txt_draw[]"><br><br>
<input type="submit" value="Submit">
</form>
Here is the Controller:
$win = $request->txt_win;
$loss = $request->txt_loss;
$draw = $request->txt_draw;
$checkValue = $request->txt_check ;
foreach $checkValue as $key => $value) {
$result[] = Model::create([
'checkValue' => $value,
'winning' => $win [$key],
'lost' => $loss [$key],
'draw' => $draw [$key],
]);
}
This code works well for the first insert but when I try to second insert then insert null value like this-
I want to insert into database this way,
checkval win loss draw
A 2 3 4
B 3 4 3
C 4 5 5
How can I do this. I need help. Advanced thanks.
Your code is missing a circular brace on the foreach loop.
Change this
foreach $checkValue as $key => $value) {
$result[] = Model::create([
'checkValue' => $value,
'winning' => $win [$key],
'lost' => $loss [$key],
'draw' => $draw [$key],
]);
}
to this
foreach ($checkValue as $key => $value) {
$result[] = Model::create([
'checkValue' => $value,
'winning' => $win [$key],
'lost' => $loss [$key],
'draw' => $draw [$key],
]);
}

Laravel 8 - Login Authentication Failed

Im new to Laravel and i have an error when i tried to login into my user, I have tried to identify the mistake and i think it would be in the auth()->attempt in SessionsController.php.
I tried to ddd($attributes); before the auth()->attempt and the input is there but it failed in auth()->attempt. So i tried ddd(auth()->attempt) and i got false.
If anyone know how to fix this please help me :(
This is my error
Below is my code:
routes/web.php:
Route::get('login', [SessionsController::class, 'create'])->middleware('guest');
Route::post('login', [SessionsController::class, 'store'])->middleware('guest');
sessions.create.blade.php (Login Page)
<form method="POST" action="/login" class="mt-10">
#csrf
<!-- Email -->
<div class="mb-6">
<label for="email" class="block mb2 uppercase font-bold text-xs text-gray-700">
Email
</label>
<input type="email" class="border border-gray-400 p-2 w-full" name="email" id="email" value="{{ old('email') }}" required>
#error('email')
<p class="text-red-500 text-xs mt-1">{{ $message }}</p>
#enderror
</div>
<!-- Password -->
<div class="mb-6">
<label for="password" class="block mb2 uppercase font-bold text-xs text-gray-700">
Password
</label>
<input type="password" class="border border-gray-400 p-2 w-full" name="password" id="password" required>
#error('password')
<p class="text-red-500 text-xs mt-1">{{ $message }}</p>
#enderror
</div>
<!-- Submit -->
<div class="mb-6">
<button type="submit" class="bg-blue-400 text-white rounded py-2 px-4 hover:bg-blue-500">
Log In
</button>
</div>
</form>
create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username')->unique();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $guarded = [];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt('$password');
}
public function posts()
{
return $this->hasMany(Post::class);
}
}
SessionsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades;
class SessionsController extends Controller
{
public function create()
{
return view('sessions.create');
}
public function store()
{
$attributes = request()->validate([
'email' => 'required|email',
'password' => 'required',
]);
// ddd($attributes);
///ddd(auth()->attempt($attributes));
if (auth()->attempt($attributes)) {
return redirect('/')->with('success', 'Welcome Back!');
}
throw ValidationException::withMessages(['email' => 'Your provided credentials could not be verified.']);
}
public function destroy()
{
auth()->logout();
return redirect('/')->with('success','Goodbye!');
}
}

Retrive ids and check related boxes

Using
Laravel 8.54
Livewire 2.6
Laratrust package for roles and permissions
I want to edit the permissions role like that
RolesEdit.php (livewire component)
<?php
namespace App\Http\Livewire\Admin\Roles;
use App\Models\Role;
use Livewire\Component;
use App\Models\Permission;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
class RolesEdit extends Component
{
public $data = [];
public $role;
public $selectedIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
}
public function update()
{
$this->data['permissions'] = $this->selectedIds;
$validated = Arr::except($this->validatedData(), ['permissions']);
$this->role->update($validated);
$this->role->permissions()->sync($this->data['permissions']);
}
public function validatedData()
{
return Validator::make($this->data, [
'display_name' => 'required',
'description' => 'required',
"permissions" => "required|array|min:1",
"permissions.*" => "required|distinct|min:1",
])->validate();
}
public function render()
{
$permissions = Permission::all();
return view('livewire.admin.roles.roles-edit', compact('permissions'));
}
}
Roles-edit.blade.php
<div class="mt-1">
<label class="form-label">{{ __('site.display_name') }}</label>
<input wire:model="data.display_name" type="text" class="form-control" placeholder="Enter role name" />
</div>
<div class="mt-1">
<label class="form-label">{{ __('site.role_description') }}</label>
<textarea wire:model="data.description" type="text" class="form-control"
placeholder="Enter Description"></textarea>
</div>
<div class="row w-100">
#foreach ($permissions as $permission)
<div class="col-md-3">
<div class="form-check ms-5">
<input wire:model.defer="selectedIds" class="form-check-input" id="{{ $permission->name }}"
value="{{ $permission->id }}" type="checkbox"
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }} />
<label class="form-check-label" for="{{ $permission->name }}">
{{ $permission->display_name }}</label>
</div>
</div>
#endforeach
</div>
When I open roles-edit view I want to check boxes that have $permission->id related to role so I use
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
But it did not work … all checkboxes is unchecked
instead using code:
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
try this
#if($role->permissions->contains($permission->id)) checked #endif
also try to add wire:key directive to the parent div of the input element
<div class="form-check ms-5" wire:key="input-checkbox-{{ $permission->id }}">
I suggest you, create an array to retrieve the permissions ids of the role
public $permissionsIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
$this->permissionsIds = $this->role->permissions()->pluck('id');
}
// in blade
#if(in_array($permission->id,$permissionsIds)) checked #endif

How to upload image file on codeigniter 3?

I've tried everything to code upload the image file but I still stuck and it keeps an error. It can't detect the data of the image file so it can't store to the database when I submitted the form. I saw every tutorial I've been searched and look into my code seems everything right but why it still keeps an error.
Controller
public function create()
{
if (!$this->session->userdata('user_logged')) {
redirect('Auth');
}
$data["title"] = "Form Create Blog";
$data["landingpage"] = false;
$data['content'] = 'component/admin/blog/blog_create';
$this->form_validation->set_rules('blogTitle', 'Title tidak boleh kosong', 'required|max_length[50]');
$this->form_validation->set_rules('blogHeaderImg', 'Header Image tidak boleh kosong', 'required');
$this->form_validation->set_rules('blogKeyword', 'Keyword tidak boleh kosong', 'required|max_length[50]');
$this->form_validation->set_rules('blogContent', 'Content tidak boleh kosong', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('index', $data);
} else {
$config['upload_path'] = realpath(APPPATH . '../assets/img/upload/blog/header_image');
$config['allowed_types'] = 'jpg|png|PNG';
$nmfile = time() . "_" . $_FILES['blogHeaderImg']['name'];
$config['file_name'] = $nmfile;
$this->load->library('upload', $config);
if (!$this->upload->do_upload("blogHeaderImg")) {
$error = array('error' => $this->upload->display_errors());
echo '<div class="alert alert-danger">' . $error['error'] . '</div>';
} else {
$data = array('upload_data' => $this->upload->data());
$header_image = $data['upload_data']['file_name'];
$this->M_Blog->storeBlogData($header_image);
print_r($_FILES['blogHeaderImg']);
$this->session->set_flashdata('flashAddBlog', 'Data berhasil <strong>ditambahkan</strong>');
redirect('blog');
}
}
}
Model
public function storeBlogData($header_image)
{
$data = [
'title' => $this->input->post('blogTitle', TRUE),
'header_image' => $header_image,
'content' => $this->input->post('blogContent', TRUE),
'blog_keyword' => $this->input->post('blogKeyword', TRUE),
'created_by' => $this->session->userdata('user_logged')->id,
'last_modified_by' => $this->session->userdata('user_logged')->id,
'is_deleted' => 'n'
];
$this->db->insert('blog', $data);
}
View
<form method="POST" action="create" enctype="multipart/form-data">
<div class="form-group">
<label for="blogTitle">Title</label>
<input class="form-control" type="text" name="blogTitle" id="blogTitle" placeholder="Title">
<small class="form-text text-danger"><?= form_error('blogTitle') ?></small>
</div>
<div class="form-group">
<label for="blogHeaderImg">Header Image</label>
<input class="form-control-file" type="file" id="blogHeaderImg" name="blogHeaderImg">
<small class="form-text text-danger"><?= form_error('blogHeaderImg') ?></small>
</div>
<div class="form-group">
<label for="blogKeyword">Keyword</label>
<input class="form-control" type="text" id="blogKeyword" name="blogKeyword" placeholder="Keyword">
<small class="form-text text-danger"><?= form_error('blogKeyword') ?></small>
</div>
<div class="form-group">
<label for="blogContent">Content</label>
<textarea class="form-control" type="text" id="blogContent" name="blogContent" placeholder="Content" rows="10"></textarea>
<small class="form-text text-danger"><?= form_error('blogContent') ?></small>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
already solved. I just have to add this code to blog controller
if (empty($_FILES['blogHeaderImg']['name'])) {
$this->form_validation->set_rules('blogHeaderImg', 'Document', 'required');
}
instead of using this code
$this->form_validation->set_rules('blogHeaderImg', 'Header Image tidak boleh kosong', 'required');
thank you

Aurelia Validation - one of two fields must be mandatory

<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="production.Sku1">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="production.Sku2">
</div>
</div>
</div>
I have the textboxes above, either sku1 must be mandatory or sku2. I know how to do this in what seems like everything but Aurelia.
I was hoping it would be something simple like
this.validator = this.validation.on(this)
.ensure('production.StockStatusId').isGreaterThan(0).withMessage('is required')
.ensure('production.Sku1').isNotEmpty().Or.ensure('production.Sku2').isNotEmpty();
I have touched on if statements but unsure what the computedFrom would be
UPDATE
I was hoping this would work, however it isn't. Anyone know why?
.ensure('production.Sku1', (config) => {config.computedFrom(['HasProvidedEitherSku'])})
.passes(() => { return this.HasProvidedEitherSku }).withMessage("(Need to provide a SKU)")
get HasProvidedEitherSku(){
if ((this.production.Sku1 === undefined || this.production.Sku1 === null) && (this.production.Sku2 === undefined || this.production.Sku2 === null)){
return false;
} else {
return true;
}
}
UPDATE
This does work, in a way. However both show the error straight away however the error is only cleared on the one that has become valid. I understand why as the error message is attached to each one sep, however I dont know how to stop this
.ensure('production.Sku1', (config) => {config.computedFrom(['HasProvidedEitherSku'])})
.if(() => { return this.HasProvidedEitherSku })
.isNotEmpty().withMessage('a SKU is required')
.endIf()
.ensure('production.Sku2', (config) => {config.computedFrom(['HasProvidedEitherSku'])})
.if(() => { return this.HasProvidedEitherSku })
.isNotEmpty().withMessage(‘a SKU is required')
.endIf();
Here is what I have used:
HTML
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="Sku1">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label"> SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="Sku2">
</div>
</div>
Validation
.ensure('Sku1', (config) => {config.computedFrom(['Sku1, Sku2'])})
.if(() => { return this.HasProvidedEitherSku1OrSku2 === false })
.isNotEmpty().withMessage(‘at least one sku is required')
.hasLengthBetween(0, 50)
.endIf()
.ensure('Sku2', (config) => {config.computedFrom(['Sku1, Sku2'])})
.if(() => { return this.HasProvidedEitherSku1OrSku2 === false })
.isNotEmpty().withMessage(‘at least one sku is required’)
.hasLengthBetween(0, 50)
.endIf();
Validation Method
get HasProvidedEitherSku1OrSku2 (){
if ((this.Sku1 === undefined || this.Sku1 === null || this.Sku1 === '') && (this.Sku2=== undefined || this.Sku2=== null || this.Sku2=== '')){
return false;
} else {
return true;
}
}