request()->validate() does not work the second time around n laravel 8 - laravel-8

I have a method to store and validate data from POST request, the first method works fine and validated successfully.
public function saveClientInfo(){
ClientInfo::create($this->validateClientInfo());
}
public function validateClientInfo(){
return request()->validate([
'code' => 'required',
're' => ['required','unique:client_infos'],
'name' => 'required',
'contact' => 'required',
'email' => 'required',
'property' => 'required',
'status' => 'required'
]);
}
Here in this second method with the same structure for saving and validating the requests, it doesn't work I'm very intrigue as to why.
public function loanStatus(){
PaymentInfo::create($this->validatePay());
}
public function validatePay(){
return request()->validate([
'payment_type' => 'required',
'terms' => 'required',
'amount_due' => 'required',
'from' => 'required',
'to' => 'required'
]);
}
By the way they're in the same controller so I dont get nauseous trying to figure out what is the difference of both as to where I went wrong.
NOTE:
the error it gives is Route GET is not Supported suggested Method
POSTS some sort of like this,
that's why it's confusing enough already I checked the form and routes and I used post so why this error is showing so I figure it must be the request validate part.
Blade File
<form action="/proceed/loan-status" method="POST">
#csrf
<input type="hidden" name="re" value="{{ $re }}">
<div class="row">
<div class="p-2">
<input type="text" class="form-control" name="payment-type" placeholder="Payment Type...">
#if($errors->has('payment_type'))
      <p class="alert text-danger">{{ $errors->first('payment_type') }}</p>
#endif
</div>
<div class="p-2">
<input type="text" class="form-control" name="terms" placeholder="Terms...">
</div>
<div class="p-2">
<input type="number" min="2" max="" step="any" class="form-control" name="amount" placeholder="Amount Due...">
</div>
<div class="p-2">
<input type="text" class="form-control" name="from" placeholder="From...">
</div>
<div class="p-2">
<input type="text" class="form-control" name="to" placeholder="To...">
</div>
</div>
</div>
<div class="card-footer d-flex justify-content-between">
<button type="submit" class="btn btn-success btn-sm">Save</button>
Cancel
</div>
</form>
web.php
Route::post('/proceed/loan-status', 'ClientInfoController#loanStatus');

If your Laravel version is 8, change the route sintax
Route::post('/proceed/loan-status', ClientInfoController::class,'loanStatus')->name('proceed.loan-status');
and in the blade form change the action to
<form action="{{ route('proceed.loan-status') }}" method="POST">
Also, I suggest you use validation request like Laravel doc, it's a better coded controller and adjusted to patterns. Changing that, you must have something like
public function loanStatus(StorePaymentInfoRequest $request){
PaymentInfo::create($request->validated());
}
and in the StorePaymentInfoRequest
/**
* 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
*/
public function rules()
{
return [
'payment_type' => 'required',
'terms' => 'required',
'amount_due' => 'required',
'from' => 'required',
'to' => 'required'
];
}

Please use the laravel's request validation.
php artisan make:request FormRequest
It will generate a file that you can use.
https://medium.com/#kamerk22/the-smart-way-to-handle-request-validation-in-laravel-5e8886279271
This Article is a good example.

The error look like you have defined post route in web.php but you are requesting form method is GET or vice versa .So it throwing error
So you need to change form method to post to support that
<form method="POST" >
Or if you still need get request in form method then you need to update routes form post to get

in your Route put your code like this
ROUTE::POST('/VARRIBALE NAME', [CONTROLLER NAME::CLASS, 'FUNCTIONNAME']->NAME('VARRIBALE NAME.FUNCTIONNAME);

Related

Missing required parameters for [Route: password.reset] [URI: {locale}/password/reset/{token}]

Listed below are code listings in which changes have been made. The authorization and registration system works well. The only problem is resetting the password.
web.php
Route::get('/', function() {
return view('index');
});
Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale'
], function () {
Route::get('/', function () {
return view('index');
});
Auth::routes();
});
head
<head>
...
<meta name="csrf-token" content="{{ csrf_token() }}">
...
</head>
email.blade.php
#extends('layouts._main')
#section('content')
<section class="main_section">
<div class="auth_wrapper">
<div class="form_container">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<form method="POST" action="{{ route('password.email', app()->getLocale()) }}" class="auth_login">
#csrf
<div class="auth_form_titles">
<h1 class="auth_form_title">#lang('forgot.caption')</h1>
</div>
<div class="auth_form_text">#lang('forgot.text')</div>
<input id="email" type="email" name="email"
#if($errors->has('email')) class="fields_error" #else class="fields" #endif
placeholder="#lang('forgot.email_field')" title="#lang('forgot.email_field')"
value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="validation_error">{{ $message }}</span>
#enderror
<button type="submit" class="buttons button_login">#lang('forgot.button2')</button>
</form>
</div>
</div>
</section>
#endsection
If now I click on the button "Send Password Reset Link", I get an error.
result
Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameters for [Route: password.reset] [URI: {locale}/password/reset/{token}].
Please tell me how to solve this problem.
This is a publicly shared error: https://flareapp.io/share/lm2GgDPx#F61
In order for the error not to appear in the described scheme, it is enough to make the prefix parameter optional (?), And also list the languages with a regular expression, as in the listing below:
Route::group([
'prefix' => '{locale?}',
'where' => ['locale' => '^ru|en$'],
'middleware' => 'setlocale'
], function () {
Route::get('/', function() {
return view('index');
});
Auth::routes();
});

Post inside controller not loading into model in Yii2

When I want to get the variable from the form the post action doesn't load .
This is my view:
<?php
$form = ActiveForm::begin();
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?= Html::a(Yii::t('app', 'Start'), ['start', 'link' => $model->link], ['type' => 'button','class' => 'btn btn-primary btn-round']) ?>
</div>
<?php ActiveForm::end(); ?>
This is my controller:
if ($model->load(Yii::$app->request->post())){
exit(var_dump('everything is ok'));
}else {
exit(var_dump('nothing is right'));
}
The result is 'nothing is right'.
Apart from using the anchor link instead of a submit button, you are not using model to create active input hence the field names are without model names or the standard array format that Yii accepts, you should pass empty string to the load method as second parameter which is formName like below
$model->load(Yii::$app->request->post(),'');
So your complete form should look like
<?php
$form = ActiveForm::begin(
[
'action' => 'start',
]
);
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?php echo Html::submitButton(Yii::t('app', 'Start'), ['class' => 'btn btn-primary btn-round']) ?>
</div>
<?php ActiveForm::end();?>
EDIT
and your controller code should look like below, mind the first check it needs to be there so that the code is run when you submit only not on page load
if (Yii::$app->request->isPost) { //this should be here before the rest of the code
if ($model->load(Yii::$app->request->post(), '')) {
exit(var_dump('everything is ok'));
} else {
exit(var_dump('nothing is right'));
}
}
This is because load() method looks for post data inside model name property and you are writing the input yourself instead of using the Yii method for forms.
So your post Yii::$app->request->post() returns:
array(
'username' => 'value of username',
)
And your $model->load looks for
array(
'modelName' => array(
'username' => 'value of username',
)
)
To make your post data too look like that you could do it the right way that is, delete your Input and use this method inside the form:
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
Or the wrong way, modify your input and inside username use:
<input type="text" name="modelName[username]" placeholder="FullName">
Of course where I put username you must put your real model name.
Finally I find the solution
<?php
$form = ActiveForm::begin(
[
'action' => 'start',
]
);
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?= Html::a('submit', Url::to(['start', 'link' => $model->link]), ['data-method' => 'POST']) ?>
</div>
<?php ActiveForm::end();?>
thank you for all

How to save category in laravel 5.7 with vue.js

Using Laravel 5.7 with vuejs, I am trying to display parent_id from a MySQL categories table. I want to pass the name and get all it's child categories irrespective of the parent.
My blade
<form action="{{ route('categories.store') }}" method="post">
#csrf
<div class="form-group">
<label for="name">name:</label>
<input type="text" id="name" class="form-control" v-model="name">
</div>
<div class="form-group">
<label for="sub_category">category</label>
<select id="sub_category" v-model="parent_id" class="form-control">
<option data-display="main category" value="0">main category</option>
<option v-for="category in categories" :value="category.id">#{{ category.name }}</option>
</select>
</div>
<div class="form-group">
<button type="button" #click="addCategory()" class="btn btn-info">save</button>
</div>
</form>
web.php
Route::group(['namespace' => 'Admin', 'prefix' => 'admin'],function (){
$this->get('panel', 'PanelController#index')->name('panel.index');
$this->resource('categories', 'CategoryController');
});
My vue
addCategory: function () {
axios.post(route('categories.store'), {
name: this.name,
parent_id: this.parent_id,
}).then(response => {
this.categories.push({'name': response.data.name, 'id': response.data.id});
}, response => {
this.error = 1;
console.log('Errors');
});
}
CategoryController
public function store(Request $request)
{
$category = new Category();
$category->name = $request->name;
$category->parent_id = $request->parent_id;
if ($category->save()) {
return $category;
}
}
I see this error in console for first
Too
And I get 405 error.
Remove #click from submit buttom.
Remove route... from form action and set it #
Add #submit="addCategory()" to the form
In the axios.post samply add the route without route function.
Update:
If you want to prevent page refreshing, add .prevent after #submit.

Laravel 5.7 Auth::attempt return false

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'))
]);

reset password does not work with mailgun configuration

I configured laravel 5.1 according to mail docs. Sending mail works fine.
Next step was to add the reset password according to resetting passwords docs. Here I struggle to send the link to the reset-password formular.
Seems like the function to send the reset mail is not triggered. I checked as well with the config/mail.php configuration pretend = true;. There was no entry in the logfile, that a email was send.
Somehow its as well hard to debug, as I could not find the function where the reset email is triggered.
How do I send the reset password with mailgun?
Where is the function locate to send the reset password, or where can I overwrite it, to test it?
This are my configurations:
.env
# ...
MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mail.org
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAILGUN_DOMAIN=mg.foo.com
MAILGUN_SECRET=key-foobar.etc
# ....
config/service.php
//...
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
//...
config/mail.php
// ...
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => ['address' => 'foo#test.com', 'name' => 'foo'],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'pretend' => false,
// ...
app/Http/routes.php
// ...
Route::group([
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
], function() {
//Route::controllers([ 'password' => 'Auth\PasswordController', ]);
// works only if the user is logged out!!!1
// Password reset link request routes...
Route::get('password/email', 'Auth\PasswordController#getEmail');
Route::post('password/email', 'Auth\PasswordController#postEmail');
// Password reset routes...
Route::get('password/reset/{token}', 'Auth\PasswordController#getReset');
Route::post('password/reset', 'Auth\PasswordController#postReset');
});
//...
resources/views/auth/password.blade.php
#extends('layout')
#section('content')
<div class="container">
<form method="POST" action="/password/email">
{!! csrf_field() !!}
#if (count($errors) > 0)
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<div class="row">
<div class="col-md-6">
{!! Form::label('email', trans( 'mes.email' )) !!}
<input type="email" name="email" value="{{ old('email') }}" class="form-control">
</div>
<div class="col-md-8">
<button type="submit" class="btn">
Send Password Reset Link
</button>
</div>
<div>
</form>
</div>
#endsection
Incorrect routes was the problem. The example from the docs did hardcode the action value in the form element.
This did not reflect my routes configuration. With the following changes the password reset email works:
app/Http/routes
// change route to a named route
// Route::post('password/email', 'Auth\PasswordController#postEmail');
Route::post('password/email', ['as' => 'password.email', 'uses' => 'Auth\PasswordController#postEmail']);
resources/views/auth/password.blade.php
<!-- Use the named route in the form builder and remove csrf_field -->
{!! Form::open(['route' => 'password.email']) !!}