Laravel validation with Bootstrap Modal - php

I've included this Github script to make a validation form with Bootstrap Modal everything is set up correctly but when I included this script the form don't submit because there are some errors which is good but it doesn't show them in the view
Controller
$this->validate($request, [
'nom' => 'required|unique:filieres'
]);
View
#if($errors->get('nom'))
#foreach($errors->get('nom') as $error)
<li class="has-error">{{$error}}</li>
#endforeach
#endif

can you just type this code in your view file
#include('includes.form_error')
second type this in your controller
public function store(UsersRequest $request)
{
}
and you create UserRequest file in Requests folder and type this
public function rules()
{
return [
'name' => 'required',
];
}
after you got proper error

Related

Do you know why the named bag messages are not appearing?

I have a page that has a form with a select menu and if there are some validation errors in that form the validation errors are shown using "#include('includes.errors')". But in this same page I have a button that when the user clicks in it it shows a modal where the user can introduce a subject, a message to send an email. In this modal I also have "#include('includes.errors')".
Issue: So the issue is that if there are validation errors in the form in the modal because the subject or messare were not filled by the user that errors appear on the modal but also on the same page above the form that has the select menu. Also if there are some validation errors in the form that has the select menu and the user opens the modal that validation erros also appear in the modal.
To fix this issue using named bags is not working. For example in the storeQuantities() there is:
public function storeQuantities(Request $request, $id, $slug = null)
{
$validator = $request->validate([
'rtypes' => ['required', 'array', new RegistrationTypeQuantity],
]);
// dd('test'); dont shows
if ($validator->fails())
{
return redirect()->back()->withErrors($validator, 'quantitiesError');
}
...
}
In the contactOrganizer:
public function contactOrganizer($id, Request $request)
$validator = $this->validate($request, $rules, $customMessages);
// dd('test'); dont shows
if ($validator->fails())
{
return redirect()->back()->withErrors($validator, 'contactErrors');
}
}
And then use:
#include('includes.errors', ['errors' => $errors->quantitiesError])
And in the modal:
#include('includes.errors', ['errors' => $errors->contactErrors])
But its not working it appears always that the bag is empty in both cases with "{{dump($errors->contactErrors)}}" and "{{dump($errors->quantitiesError)}}" like:
"MessageBag {#336 ▼
#messages: []
#format: ":message"
}"
It seems that the issue is because there is some error in "$validator = $this->validate($request, $rules, $customMessages);", any code after this line like "dd('test);" dont appears.
Laravel will automatically redirect the user back to their previous location when $this->validate is used
You need to use Validator::make instead Manually Creating Validators
$validator = Validator::make($request->all(), [
'rtypes' => ['required', 'array', new RegistrationTypeQuantity],
]);
if ($validator->fails())
// redirect with errors
}
And don't forger to include use Validator;

Laravel Post Request

I have a table called Customer and with a Get Request I can already get all the Data (which I created with phpMyAdmin) on a HTML Template.
Now I want to create a new Customer with a Post Request.
This is the way I thought it would work:
In the Controller:
public function addNewCustomer(Request $request)
{
return \app\model\Customer::create($request->all());
}
The route:
Route::post('posttest', 'CustomerController#addNewCustomer');
How can I create a validation for it?
You can add validation of form like below in addNewCustomer,
public function addNewCustomer(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
return \app\model\Customer::create($request->all());
}
For more information about input validation in Laravel Please readout Laravel Validation Documentation

Using controller to edit database on click in Laravel 5.4

I'm trying to have a button pass a query to the database when it's clicked. I'd like to have this set within a Controller that also stores requests and deletes requests. I was able to write to the database using store() and destroy(), but my edit() function gives me routing trouble. What is the best method to edit records using a controller? How would you build the edit() function? Or...should I be using the Update() function? I'm a Laravel/PHP beginner, please explain your answers if you can. Thank you!!
Overview: The project is an employee records table. I want to click a button that changes the employment status of an employee. I already have buttons to add new employee and delete and employee using this same Controller.
This is the route I set for the page:
Route::resource('employees', 'EmployeeController');
This is the front end form code for the button:
$workers = DB::table('employees')->get();
#foreach($workers as $employee)
{!! Form::open(array(
'method' => 'edit',
'route' => [ 'employees.edit', $employee->id]
)
)
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
#endforeach
This is my store function and destroy function:
public function store(Request $request)
{
// Confirm Both Fields Are Not Empty
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
]);
//Add a new employee using the request data
$employee = new Employee;
$employee->first_name = request('first_name');
$employee->last_name = request('last_name');
$employee->position = request('position');
$employee->salary = request('salary');
$employee->hire_date = request('hire_date');
//$employee->attach = request('attach');
//Save it to the database
$employee->save();
//And then redirect back to the Employees page
return redirect('/employees');
}
public function destroy($id)
{
$employee = Employee::find($id);
$destroysignal = $employee->delete();
if($destroysignal) {
return redirect('employees');
}
}
You don't edit records, you update them. In your case you need an update() function in your controller
public function update(Request $request, $id)
{
$employee = Employee::findOrFail($id);
$employee->employment_status = true; //or false or whatever your statuses are
$employee->update();
return redirect()->back()->with('message', 'Employee updated!');
}
In your form, use the update route instead
{!! Form::model($employee, [
'method' => 'PATCH',
'route' => ['employees.update', $employee->id]])
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
When using resource routes, 'route' => [ 'employees.edit', $employee->id] will most like to open a page where you want to edit the object. And the route will be bound to the edit($id) function of your controller.
With that said, the edit route doesn't need a form. A simple anchor would do
Edit Employee

ProfileController#store is not send post method and not save any data to profile table

I am new with PHP and Laravel.
I am using Laravel Framework version 5.3.29 and PHP 7
I am making extend register form with two parts.
register form which makes login credentials; Username and password
and after login credentials has been created, second part is creating profile to new user.
Process: Register form save data to user table and use user model.
after succesfully created username & password, it will redirect to
profile form and send post data to proceed form and validation.
Profile form is using profile model.
1) how to troubleshoot, when data has been sent by post method and n there is no error message. it only return back to profile form after submit button has been pressed.
2) I can see there is no data save to profile table.
register (user table) and profile table are in same database as
register form can save it, database part works fine.
code skeleton has made from "php artisan make:auth
complete code can be found https://github.com/mikromika/project1/
my route file is following:
// Registration Routes
Route::get('auth/register', 'Auth\RegisterController#getRegister');
Route::post('auth/register', 'Auth\RegisterController#register');
// Show profile form
Route::get('bio/create', ['as' => 'bio.create', 'uses' => 'Bio\ProfileController#create']);
Route::post('bio/store', ['as' => 'bio.store', 'uses' => 'Bio\ProfileController#store']);
ProfileController:store
this should validate data and save it to profile table
public function store(Request $request)
{ $this->validator($request->all())->validate();
$this->guard()->login($this->createx($request->all()));
Session::flash('success', 'Data was successfully save!');
if ($exception instanceof TokenMismatchException) {
Session::flash('success', 'Data was failed to save!');
return redirect('/auth/login');
}
// show profile form info after success post; does not work yet
return redirect()->route('bio.show'); }
Here is profile form way to send post method.
<form id="profile-form" action="{{ url('/bio/store') }}" method="POST" form class="form-horizontal">
{{ csrf_field() }}
post method is never reach that ProfileController:store part.
I have tried to use "GET" method, but I'm getting error
MethodNotAllowedHttpException in RouteCollection.php line 218:
I have changed route to
Route::get('bio/store', ['as' => 'bio.store', 'uses' => 'Bio\ProfileController#store']);
and form <form id="profile-form" action="{{ url('/bio/store') }}" method="GET" form class="form-horizontal">
Because form need to send by "POST" method, I understand that error!.
Here is validate part from ProfileController:validator
protected function validator(array $data) // copied from register controller
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname ' => 'required|max:255',
'email' => 'required|email|max:255|unique',
'phone' => 'integer',
'mobile' => 'integer',
]);
}
Here is ProfileController:createx part
I took it from registerController.
protected function createx(array $data) //copied from register controller
{ // was dublicate name "create"
return Profile::createx([ // changed to "createx"
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
]);
}
Here is profile model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
//
protected $table = 'profiles';
protected $fillable = [
'firstname',
'lastname',
'email',
'phone',
'mobile',
// 'name', 'email', 'password',
];
protected $hidden = [
'status',
//'location',
];
}
Thanks to Alexey Mezenin DD() tip for troubleshoot
#MikroMika this data shows that you do not pass firstname and
lastname. Look at result of the dd($data); It should be something like
['firstname' => 'John', 'lastname' => 'Smith'] – Alexey Mezenin 20
mins ago
Now I am back to beginning,
Why form is not pass data by POST method ?
There is no createx() method in Eloquent. You defined it in a controller, but you're trying to use it with the model. Use create() method:
return Profile::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
]);
Also, you've asked how to troubleshoot. Install Laravel Debugbar. Also, using dd() helper is really helpful:
dd(Profile::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
]));

Laravel 5.3 - Custom validators

I have this validator for input called "name":
Regex:/^[A-Za-z0-9\\s\\-\\/,.]*$/|min:5|max:50
But, I want to use this validator in multiple forms in my website.
How can i do this without to copy this validator in all the forms validations?
My database contains table called "settings", every row presents setting of the website. Each setting contain Json code that save the setting data.
I want to create custom validator that check if the input value equals to one of the values in the Json code in my database.
I have Json code like this:
[{"US":"United States", "UK":"United Kingdom"}]
And I want to check if the value of the input equals to one of the values in the Json code. How can I do this?
I know you said, across your website. However, I would think that you're ensuring that the use of forms using the same validators are relatively within the same state.
Here's an example that helped me get to where I needed to be! I hope it serves as a good enough guide!:
MessageBag documentation here: http://laravel.com/docs/5.0/validation#error-messages-and-views
public function postLogin(Request $request)
public function postLogin(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email', 'password' => 'required',
]);
if ($validator->fails())
{
return redirect($this->loginPath())->withErrors($validator, 'loginErrors');
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
], 'loginErrors');
}
Now you can look for errors inside of your view:
#if (!$errors->loginErrors->isEmpty())
<div class="form_error_login">
<strong>Whoops!</strong> There were some problems with your input.<br> <br>
<ul>
#foreach ($errors->loginErrors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
For the Modals (if you use them):
<script>
$findError = $('div').find ('div');
if ( $findError.hasClass('form_error_login')){
$('#modalLogin').foundation('reveal', 'open');
}
if ( $findError.hasClass('form_error_register')){
$('#modalRegister').foundation('reveal', 'open');
}
</script>
Reference:
https://laracasts.com/discuss/channels/laravel/authcontroller-loginregistration-on-same-page

Categories