I'm using toastr notification in my app. I send the notification when the form submit is failed due to validation or when the form submit is succeed. I usually do it this way :
public function store(Request $request) {
$data = $request->all();
$rules = [
'name' => 'required|string',
'email' => 'required|email',
'message' => 'required|string',
'g-recaptcha-response' => 'required|captcha',
];
$validate = Validator::make($data, $rules);
if ($validate->fails()) {
$error = array(
'message' => "Error sending the message!",
'alert-type' => 'error'
);
return back()->withErrors($validate)->withInput()->with($error);
}
Feedback::create($data);
$success = array(
'message' => "Thanks for the feedback! Your message was sent successfully!",
'alert-type' => 'success'
);
return redirect()->route('contactus')->with($success);
}
But when the table columns number is large (10 columns or more) I'd like to use Form Request Class instead rather than declaring the rules in the store method. So it became like this :
public function store(FeedbackRequest $request) {
$data = $request->all();
Feedback::create($data);
$success = array(
'message' => "Thanks for the feedback! Your message was sent successfully!",
'alert-type' => 'success'
);
return redirect()->route('contactus')->with($success);
}
The problem is, when using Form Request I don't know how to send the error notification when validation fails. Is there a way to check if Form Request Class validation failed so I can send the error notification ? That's all and thanks!
Adding After Hooks To Form Requests is exactly what you need in your Request class:
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($validator->failed()) {
$validator->errors()->add('field', 'Something is wrong with this field!'); // handle your new error message here
}
});
}
Related
I don't understand where it is blocking. If I replace the update() with a create() method, it works, or if I remove the broadcast, the update works. How to update with the broadcast?
Call to a member function load() on bool
public function SendToMarket(Request $request, $id)
{
$card = auth()->user()->cards()->findOrFail($id)->update([
'market_id' => $request["_market"],
'borderStyle_id' => $request["_borderStyle"],
'price' => $request["_price"]
]
);
$notification = array(
'message' => 'Card Send to market Successfully !',
'alert-type' => 'warning'
);
broadcast(new FetchCardEvent($card->load('user')))->toOthers();
return redirect()->route('user.cards')->with($notification);
}
update() does not return the Modal instance. Instead it will return a Boolean.
After retrieving the card using firstOrFail() you should update it separately.
public function SendToMarket(Request $request, $id) {
$card = auth()->user()->cards()->findOrFail($id);
$card->update([
'market_id' => $request["_market"],
'borderStyle_id' => $request["_borderStyle"],
'price' => $request["_price"]
]);
$notification = array(
'message' => 'Card Send to market Successfully !',
'alert-type' => 'warning'
);
broadcast(new FetchCardEvent($card->load('user')))->toOthers();
return redirect()->route('user.cards')->with($notification);
}
This is contact form. I would like to recive email and save this data to my mysql. I use Laravel. Email function works good. but There is a problem. I would like to store all data at "function complete".
I validate all data at "function confirm" This is confirm screen page so user still not submit yet. I tried to write code like this at "function complete" but error say "Undefined variable: request" Could you teach me how to fix my code please?
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put($data);
return view('mail.confirm', compact("data"));
}
public function complete()
{
$data = $request->all(); # 3)
$request->session()->put($data); # 4)
Contact::create($request->all());
$data = session()->all();
Mail::send([ ・・・
You have to pass the parameter type $request as you did in confirm function.In your complete function, you don't declare $request variable and accessing it without declaration
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
// setting session key value for you data
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
// after confirm button click get data from session with key '#data' ;
$data = $request->session()->pull('data');
// get token value in variable and remove from data set so we can use mass assignement
$token = array_shift($data);
// creating record
$Contact = Contact::create($data);
Mail::send(['text' => 'mail.temp'], $data, function($message) use($data){
$message->to($data["email"])->bcc('lara_admin#sakura.ne.jp')->from('1110.ne.jp')->subject('thnak you。');});
Mail::send(['text' => 'mail.admintemp'], $data, function($message) use($data){
$message->to('lara_admin#sakura.ne.jp')->from('emailconf#.ne.jp')->subject('you got order');});
$data = session()->regenerateToken();
return view('mail.complete');
}
I have a form where users can edit a branch's info, once the user submits that form, the update() method checks for the validity of the submitted data such as the description must be unique to every subscriber. While the validation WORKS, it doesn't redirect to the exact url/page that I want if the validation fails. It stays in the same edit form.
here's the code of my update() method:
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$this->validate($request, [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
], $messages);
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Note: the url of the edit form is /branch/edit/{id} while the page I want to redirect after submission is /branches.
Is my validation wrong? Did I miss something?
Thanks! :)
According to the laravel docs you can redirect to a different route by using the Validator facade
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$validator = Validator::make($request->all(), [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
],
$messages);
if ($validator->fails()) {
return redirect('/branches')
->withErrors($validator)
->withInput();
}
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Make sure you use the Validator facade at the beginning of your controller file use Validator;
When using the validation like below with custom messages how is possible to check if the validation fails?
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$this->validate($request, $rules, $customMessages);
Like below, without custom messages is possible to use $validator->fails() but in the above case how to verify if the validation fails?
$validator = Validator::make($request->all(), [
//...
]);
if ($validator->fails()) {
//...
}
When you use $this->validate it validate your request against your validation rules and if failed then it redirect to previous page with validation message. If you want to use $validator->fails() then use Validator::make with custom message. Like this
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$validator = Validator::make($request->all(), $rules, $customMessages);
if ($validator->fails()) {
//...
}
Check validator make method https://laravel.com/api/5.0/Illuminate/Validation/Factory.html#method_make
much simpler solution is to use custom handler in app\Exceptions\Handler.php:
public function register()
{
$this->renderable(function (ValidationException $e, $request) {
//list of specific failed tests
$e->validator->failed();
return response()->json(['message' => 'custom message','meow'=>'meow',$e->status);
});
}
this way you keep old behavior AND can still change messages sent back to the user/frontend
I'm trying to implement one of Laravel's new features "Custom Validation Rules" and I'm running into the following error:
Object of class Illuminate\Validation\Validator could not be converted to string
I'm following the steps in this video:
New in Laravel 5.5: Project: Custom validation rule classes (10/14)
It's an attempt Mailgun API's Email Validation tool.
Simple form that requests: first name, last name, company, email and message
Here is my code:
web.php
Route::post('contact', 'StaticPageController#postContact');
StaticPageController.php
use Validator;
use App\Http\Validation\ValidEmail as ValidEmail;
public function postContact(Request $request) {
return Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
}
ValidEmail.php
<?php
namespace App\Http\Validation;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as Guzzle;
class ValidEmail implements Rule
{
protected $client;
protected $message = 'Sorry, invalid email address.';
public function __construct(Guzzle $client)
{
$this->client = $client;
}
public function passes($attribute, $value)
{
$response = $this->getMailgunResponse($value);
}
public function message()
{
return $this->message;
}
protected function getMailgunResponse($address)
{
$request = $this->client->request('GET', 'https://api.mailgun.net/v3/address/validate', [
'query' => [
'api_key' => env('MAILGUN_KEY'),
'address' => $address
]
]);
dd(json_decode($request->getBody()));
}
}
Expectation
I'm expecting to see something like this:
{
+"address": "test#e2.com"
+"did_you_mean": null
+"is_disposable_address": false
+"is_role_address": false
+"is_valid": false
+"parts": {
...
}
}
Any help is much appreciated. I've been trying to get this simple example to work for over two hours now. Hopefully someone with my experience can help!
In your controller
Try this:
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
// if valid ...
According to your route, the postContact method is the method to handle the route. That means the return value of this method should be the response you want to see.
You are returning a Validator object, and then Laravel is attempting to convert that to a string for the response. Validator objects cannot be converted to strings.
You need to do the validation, and then return the correct response based on that validation. You can read more about manual validators in the documenation here.
In short, you need something like this:
public function postContact(Request $request) {
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
// do your validation
if ($validator->fails()) {
// return your response for failed validation
}
// return your response on successful validation
}