Laravel 4 password confirm doesn't seem to work how I expect it to - authentication

I am basing my code off of a video on Laracasts.com. Here is the video. My idea is that I could use that validation method to create a user. When I try to confirm the passwords, it doesn't seem to match no matter what. My initial thought was that it is hashing the password prior to validation which causes it to return false no matter what.
Here's all of my code thus far.
Users Model
protected $fillable = ['username' ,'email', 'password'];
public static $rules = [
'username' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
];
public function isValid()
{
$validation = Validator::make($this->attributes, static::$rules);
if ($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
UsersController#Store
public function store()
{
$input = Input::all();
if (! $this->user->fill($input)->isValid())
{
return Redirect::back()->withInput()->withErrors($this->user->errors);
}
//if the user input is valid then save it and assign associated role
$this->user->save();
$this->user->assignRole(Input::get('role'));
return Redirect::to('/user')->with('flash_message', 'User added to the database!');
}
Create User View - Form
{{ Form::open(['role' => 'form', 'route' => 'user.store']) }}
<div class='form-group'>
{{ Form::label('username', 'First Name') }}
{{ Form::text('username', null, ['placeholder' => 'First Name', 'class' => 'form-control']) }}
</div>
<div class='form-group'>
{{ Form::label('email', 'Email') }}
{{ Form::text('email', null, ['placeholder' => 'Last Name', 'class' => 'form-control']) }}
</div>
<div class='form-group'>
{{ Form::label('role', 'Role') }}
{{ Form::select('role', $roles, "member", ['class' => 'form-control']) }}
</div>
<div class='form-group'>
{{ Form::label('password', 'Password') }}
{{ Form::password('password', ['placeholder' => 'Password', 'class' => 'form-control']) }}
</div>
<div class='form-group'>
{{ Form::label('password_confirmation', 'Password Confirm') }}
{{ Form::password('password_confirmation', ['placeholder' => 'Password Confirm', 'class' => 'form-control']) }}
</div>
<div class='form-group'>
{{ Form::submit('Create User', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}

What's happening is that your password_confirmation field is always empty, no matter what you enter.
This is because you are using $this->user->fill($input) within the store method. However, in your model you have
protected $fillable = ['username' ,'email', 'password'];
So, this will never fill the password_confirmation field.
If you change the fillable to the following, you should have no problems
protected $fillable = ['username' ,'email', 'password', 'password_confirmation'];

Related

how can i edit a room reservation in laravel 8.the update on the controller does not work

controller(update) :as you can see in the update i'm trying to edit the room reservation(time and date),but onlly one part work the if or the else!
public function update(Request $request, Roomreservation $roomreservation)
{
$request->validate([
'date' => 'required',
'time' => 'required',
]);
$roomreservation = Roomreservation::where('date', request('date'))->where('time', request('time'))->where('code_room', request('code_room'));
if ($roomreservation->exists()) {
return back()->with('erreur', 'The chosen room is already reserved');
}
else {
$roomreservation->update([
"date" => $request->date,
"time" => $request->time,
]);
return back()->with('message_sent', 'room reservation edited successfully!');
}
}
my form
<form method="post" action="{{ route('admin.roomreservations.update', $roomreservation->id) }}">
#csrf
#method('PUT') #method('PUT')
<div>
<div>
<label for="date">Date</label>
<input type="date" min="2022-01-01" max="2022-12-31" name="date" id="date"
value="{{ old('date', $roomreservation->date) }}" />
</div>
<div>
<label for="time">Time</label>
<select name="time" id="time"
value="{{ old('time',$roomreservation->time) }}" >
<option>8H30-10H00</option>
<option>10H00-11H30</option>
<option>11H30-13H00</option>
</select>
</div>
<div>
<button>
Edit
</button>
</div>
</div>
</form>
button update on the index form
<a href="{{ route('admin.roomreservations.edit', $roomreservation->id) }}" >Update</a>
i think something is wrong on the update condition
$roomreservation = Roomreservation::where('date', request('date'))->where('time', request('time'))->where('code_room', request('code_room'));
if ($roomreservation->exists())
It seems that you're passing a wrong parameter
Change your update function to the below
public function update(Request $request, $id)
{
$request->validate([
'date' => 'required',
'time' => 'required',
]);
$roomreservation = Roomreservation::find($id);
if ($roomreservation == null) {
return back()->with('erreur', 'The chosen room does not exist');
}
if ($roomreservation->date == $request->date && $roomreservation->time == $request->time && $roomreservation->code_room == $request->code_room) {
return back()->with('erreur', 'The chosen room is already reserved');
}
else {
$roomreservation->update([
"date" => $request->date,
"time" => $request->time,
]);
return back()->with('message_sent', 'room reservation edited successfully!');
}
}

Laravel 7, How add and change key field login auth

I want to add and use a field DNI instead of email as key of login.
Something goes wrong, becouse I get this error message after write values on view login:
Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1364
Field 'dni' doesn't have a default value
(SQL: insert into users (name, email, password, updated_at, created_at) values (MAU, mau#mau.com, $2y$10$Je2/mfz40q/QApBhkA0fMOiYKy1f/ZHizHW2d8XQS7.5763bclYbq, 2020-07-22 03:31:32, 2020-07-22 03:31:32))
What I did,
I changed the users migration in order to add DNI field.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('dni')->unique();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Then I changed the model, line in app/User.php to:
protected $fillable = [
'dni', 'name', 'email', 'password',
];
I has changed app/database/factories/UserFactory.php (I dont sure if it is necesary):
$factory->define(User::class, function (Faker $faker) {
return [
'dni' => $faker->unique(),
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
I change the login and register views too, adding DNI field before email field ( app/resources/views/auth/register.blade.php):
<div class="form-group row">
<label for="dni" class="col-md-4 col-form-label text-md-right">{{ __('DNI') }}</label>
<div class="col-md-6">
<input id="dni" type="text" class="form-control #error('dni') is-invalid #enderror" name="dni" value="{{ old('dni') }}" required autocomplete="dni">
#error('dni')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
and after that, the error ocurrs.
It seems like the field "dni" is not in the model, the mysql insert not include the dni field.
Thank you for any help.
If you're using native Laravel auth components, you will need to override a few things.
There is a RegisterController in app/Http/Controllers/Auth, and you need to tell Laravel to create a user using your additional properties:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'dni' => $data['dni'],
]);
}
And you could also override the validation in the same fashion if you need it (not required though):
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'dni' => ['required'],
]);
}
If you need login to function with DNI as being mandatory, you will also need to change LoginController by overriding some of the default methods. This is a bit more complex in a way that I can't really test and verify it for your case, so you'd have to play around. But for starters:
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
'dni' => 'required|string',
]);
}
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password', 'dni');
}
If you'd like to see where does it come from, it is from an AuthenticatesUsers trait in vendor/laravel/ui/auth-backend/.

Custom wordpress taxonomy with v2 api and vue

I'm using the wordpress v2 api to display custom posttypes. Everything works as expected, only the custom taxonomy returns their ID instead of the name.
I've read that adding ?embed to the endpoint and show_in_rest adds posttypes and taxonomies to the api result and this sort of looks to be the case. But the taxonomy name isn't found in the result.
Am I missing something?
Here are some snippets of my code...
// taxonomy snippet
register_taxonomy('types',array('work'), array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'type' ),
'show_in_rest' => true,
'rest_base' => 'work-api',
'rest_controller_class' => 'WP_REST_Terms_Controller'
// custom posttype snippet
$args = array(
'labels' => $labels,
'description' => 'All projects',
'public' => true,
'menu_icon' => 'dashicons-layout',
'supports' => array('title', 'editor', 'thumbnail'),
'has_archive' => true,
'show_in_rest' => true,
'rest_base' => 'work-api',
'rest_controller_class' => 'WP_REST_Posts_Controller'
);
// DOM snippet
<div id="workfeed" class="work" style="margin-top: 100px;">
<div v-for="(item,index) in work" class="row" :data-index="index">
<div class="col">
<img :src="item._embedded['wp:featuredmedia'][0].source_url" />
</div>
<div class="col">
<h3>{{ item.title.rendered }}</h3>
{{ item.content.rendered }}
{{ item._embedded['wp:term'][0].taxonomy }}
</div>
</div>
</div>

Auto fill radio button in volt template without using model

I rendered elements of a form in volt file using below code. I want to auto fill the default radio button.
<div class="form-group" >
<div><label>Gender *:</label>
<label class="radio-inline popup-gender">{{ element }}{{ element.label()}}:</label>
</div>
If you're using PHP to prepare the form:
$radio = new Radio('my_radio', ['id' => null, 'value' => 'one']);
$radio->setDefault('one');
$form->add($radio);
$radio = new Radio('my_radio', ['id' => null, 'value' => 'two']);
$form->add($radio);
If you're using Volt:
{{ set_default('my_radio', 'one') }}
{{ radio_field('my_radio', ['id' => null, 'value' => 'one']) }}
{{ radio_field('my_radio', ['id' => null, 'value' => 'two']) }}

Add field in product Prestashop 1.7

Why is prestashop don't save my modification into database?
Using prestashop 1.7
/override/classes/Product.php
class Product extends ProductCore {
public $por_gan; public function __construct ($idProduct = null, $idLang = null, $idShop = null) {
$definition = self::$definition;
$definition['fields']['por_gan'] = array('type' => self::TYPE_INT, 'required' => false);
parent::__construct($idProduct, $idLang, $idShop); } }
In ProductInformation.php
->add('por_gan', 'Symfony\Component\Form\Extension\Core\Type\NumberType', array(
'required' => false,
'label' => $this->translator->trans('Beneficio', [], 'Admin.Catalog.Feature'),
'constraints' => array(
new Assert\NotBlank(),
new Assert\Type(array('type' => 'numeric'))
),
))
In form.html.twing
<div class="col-md-6">
<label class="form-control-label">% de beneficio</label
{{ form_widget(form.step1.por_gan) }}
</div>
Thanks
I’ve successfully added an extra tab in admin product page.
It's working fine. I think a better approach would be to create a module in order to make that modification easier to maintain.
Or you can use displayAdminProductsExtra hook, actionProductUpdate hook and actionProductAdd
The extra field is : frais_a_prevoir
I show all the files to modify but you have to check where the modification should be done inside the file (make a search and you will find)
Override /classes/Product.php
In class /classes/Product.php, there are 3 modifications to do :
1)
/** #var string Frais à prévoir */
public $frais_a_prevoir;
2)
'frais_a_prevoir' => array('type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'),
3)
$sql->select(
'p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`frais_a_prevoir`, pl.`link_rewrite`, pl.`meta_description`,
pl.`meta_keywords`, pl.`meta_title`, pl.`name`, pl.`available_now`, pl.`available_later`, image_shop.`id_image` id_image, il.`legend`, m.`name` AS manufacturer_name,
(DATEDIFF(product_shop.`date_add`,
DATE_SUB(
"'.$now.'",
INTERVAL '.$nb_days_new_product.' DAY
)
) > 0) as new'
);
In /src/PrestaShopBundle/Resources/views/Admin/Product/form.html.twig
<ul class="nav nav-tabs bordered">
<li id="tab_description_short" class="nav-item">{{ 'Summary'|trans({}, 'Admin.Catalog.Feature') }}</li>
<li id="tab_description" class="nav-item">{{ 'Description'|trans({}, 'Admin.Global') }}</li>
<li id="tab_frais_a_prevoir" class="nav-item">{{ 'frais_a_prevoir'|trans({}, 'Admin.Global') }}</li>
</ul>
<div class="tab-content bordered">
<div class="tab-pane panel panel-default active" id="description_short">
{{ form_widget(form.step1.description_short) }}
</div>
<div class="tab-pane panel panel-default " id="description">
{{ form_widget(form.step1.description) }}
</div>
<div class="tab-pane panel panel-default " id="frais_a_prevoir">
{{ form_widget(form.step1.frais_a_prevoir) }}
</div>
</div>
In /src/PrestaShopBundle/Form/Admin/Product/productInformation.php
->add('frais_a_prevoir', 'PrestaShopBundle\Form\Admin\Type\TranslateType', array(
'type' => 'Symfony\Component\Form\Extension\Core\Type\TextareaType',
'options' => [
'attr' => array('class' => 'autoload_rte'),
'required' => false
],
'locales' => $this->locales,
'hideTabs' => true,
'label' => $this->translator->trans('frais_a_prevoir', [], 'Admin.Global'),
'required' => false
))
in src/PrestaShopBundle/Model/Product/AdminModelAdapter.php:
$this->translatableKeys = array(
'name',
'description',
'description_short',
'frais_a_prevoir',
'link_rewrite',
'meta_title',
'meta_description',
'available_now',
'available_later',
'tags',
);
//define unused key for manual binding
$this->unmapKeys = array('name',
'description',
'description_short',
'frais_a_prevoir',
'images',
'related_products',
'categories',
'suppliers',
'display_options',
'features',
'specific_price',
'virtual_product',
'attachment_product',
);
2)
'frais_a_prevoir' => $this->product->frais_a_prevoir,
In database, add a column frais_a_prevoir in table product_lang
Here is an option to do this using module and does not change core files
in your MyModule.php
use PrestaShopBundle\Form\Admin\Type\TranslateType;
use PrestaShopBundle\Form\Admin\Type\FormattedTextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
public function hookDisplayAdminProductsExtra($params)
{
$productAdapter = $this->get('prestashop.adapter.data_provider.product');
$product = $productAdapter->getProduct($params['id_product']);
$formData = [
'ebay_reference' => $product->ebay_reference,
];
$formFactory = $this->get('form.factory');
$form = $formFactory->createBuilder(FormType::class, $formData)
->add('ebay_reference', TranslateType::class, array(
'required' => false,
'label' => 'Ebay reference',
'locales' => Language::getLanguages(),
'hideTabs' => true,
'required' => false
))
->getForm()
;
return $this->get('twig')->render(_PS_MODULE_DIR_.'MyModule/views/display-admin-products-extra.html.twig', [
'form' => $form->createView()
]) ;
}
public function hookActionAdminProductsControllerSaveBefore($params)
{
$productAdapter = $this->get('prestashop.adapter.data_provider.product');
$product = $productAdapter->getProduct($_REQUEST['form']['id_product']);
foreach(Language::getLanguages() as $language){
$product->ebay_reference[ $language['id_lang'] ] =
$_REQUEST['form']['ebay_reference'][$language['id_lang']];
}
$product->save();
}
in your display-admin-products-extra.html.twig
<div class="row" >
<div class="col-md-12">
<div class="form-group">
<h3>Ebay reference</h3>
{{ form_errors(form.ebay_reference) }}
{{ form_widget(form.ebay_reference) }}
</div>
</div>
</div>