How to edit the default validation message in laravel? - php

I have server validation below:
$this->validate([
'first_name' => ['required','min:2','max:30',new PersonNameRule],
'last_name' => ['required','min:2','max:30',new PersonNameRule],
'username' => ['required','confirmed',new UsernameRule],
'password' => 'required|confirmed|min:6|max:20',
'birthdate' => ['required','date',new EligibleAgeRule(21)]
]);
In front-end, I intentionally fail the validation and console.log() the errors. The log returned looks like below:
Now my question is, where is the message (The given data was invalid) came from? Can I customize it?

I don't know about your objective but if your finding the file. Its in the directory
..\Illuminate\Validation\ValidationException.php.
You can edit the message you mention inside the __construct method. See example below:
public function __construct($validator, $response = null, $errorBag = 'default') {
parent::__construct('The given data was invalid.'); //change the message here
$this->response = $response;
$this->errorBag = $errorBag;
$this->validator = $validator;
}

Related

I cannot approve incoming creator applications gives 500 | SERVER ERROR

I have a Laravel 8 project. There is a feature to approve incoming creator references. However, when I press the create button when we want to approve the incoming applications, 500 | It gives a SERVER ERROR error.
When I look from Sentry, it shows the error as follows:
ErrorException creators_store
Undefined variable $user
CreatorController::store
public function store(Request $request){
$request->validate([
'name' => 'required',
'email' => 'required|email'
]);
$subscriber = User::where('email','=',$request->email)->get()->first();
$form_id = $request->form_id;
if($subscriber!=null){
// Already registered user
$subscriber->update([
'role_id' => 3,
'name' => $request->name,
]);
$subscriber = User::findorfail($subscriber->id);
$subscriber->profile_token = env('FRONTEND_PATH').'creator-profile-form?token='.base64_encode($subscriber->email.'/'.$subscriber->id);
Mail::send(['html'=>'email.creators.register'], ['creator' => $subscriber], function($message) use($subscriber){
$message->to($subscriber->email, $subscriber->name)->subject
('Welcome to the Creator Community');
$message->from('creatorcommunity#omnicourse.io','Omnicourse Creator Community');
});
}else{
// New Creator
$pass = random_int(100000, 999999);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($pass),
'role_id' => 3,
]);
}
if($form_id!=null){
//Formdan geldi
$form = CreatorApplicationForm::findorfail($form_id);
$form->update([
'creator_id' => $user->id
]);
}
return redirect('/admin-panel/creators');
}
It was giving a similar error before, but it was because that mailgun service was not paid for. We paid for the service, but this time it started to give an error like this, but we used the same codes before and it did not give an error. I don't understand why it gives an error even though we haven't made any code changes.
Anyone know the reason or solution for this?
The issue here is that you are creating a user in the else statement, so if it never reaches the else statement (because it is true) you will never have $user.
You can either rewrite your controller somehow or do something like
if(!isset($user)){
$user = [some universal hardcode];
}

Laravel 9: testing get profile (by slug) for created row

I wrote test:
public function test_hello_world(){
$test = User::create(['name' => 'Test',
'email' => 'test#test.com',
'password' => 'password',
]);
Profile::create([
'user_id' => $test->id,
'name' => 'Test',
'slug' => 'test'
]);
$this->get('/profile/test')
->assertStatus(200);
}
What this code should testing? After get to this url it should display details about profile. If profile with this slug doesn't exist, we have error 404. In this test I create user and profile table (this 2 tables is connection) but after run test I have the error:
Expected response status code [200] but received 404. Failed
asserting that 200 is identical to 404.
Why I have this error since I created profile with this slug? For me the best option will be create testing database with a lot of records and conduct all test on it. Is it possible? How do that?
#Edit
I have a route and controller's method which display user's profile. If I go (in web browser) to localhost/profile/slug, it works, if this profile exist. My controller's method look like this:
public function show($slug) {
$profile = Profile::where('slug', $slug)
->firstOrFail();
return Inertia::render('Profile/Single', [
'profile' => $profile,
]);
}
And route:
Route::get('/profile/{slug}',
[ProfileController::class, 'show'])
->name('profile.show');
According to your requirement you have to create route for getting profile from slug name. You did wrong in single function. Without creating route it will not worked.
So below example may work for you.
For example:-
For creating data
public function createData(){
$user = User::create(['name' => 'Test',
'email' => 'test#test.com',
'password' => 'password',
]);
Profile::create([
'user_id' => $user->id,
'name' => 'Test',
'slug' => 'test'
]);
return redirect()->back()->with('success', 'Data created');
}
For Getting Data
public function getDataBySlug($slug){
$profile = Profile::where('slug',$slug)->firstOrFail();
return redirect('/dashboard')->with('slug', $slug);
}
In route file
you have to mention table name and column name {profile:slug} instead of id
Route::get('/profile/create', 'Controller#createData');
Route::get('/profile/{profile:slug}', 'Controller#getDataBySlug');
Your route definition is wrong please do as above

How to get validation message in laravel 5.5

hi folks I'm working on Laravel 5.5 and here I need to display validation messages for my API upto now I have done like this
$validator = Validator::make($request->all(),[
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
if($validator->fails)
{
$this->setMeta('status', AppConstant::STATUS_FAIL);
$this->setMeta('message', $validator->messages()->first());
return response()->json($this->setResponse(), AppConstant::UNPROCESSABLE_REQUEST);
}
Since Laravel 5.5 has some awesome validation features I am looking to validate my request like this
request()->validate([
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
But I am facing issue here what should I do to check if the validation fails? Like I was doing by if($validator->fails)
In Laravel 5.5, like the documentation mention, the validation process is very easy :
Displaying The Validation Errors :
So, what if the incoming request parameters do not pass the given
validation rules? As mentioned previously, Laravel will automatically
redirect the user back to their previous location. In addition, all of
the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error
messages to the view in our GET route. This is because Laravel will
check for errors in the session data, and automatically bind them to
the view if they are available.
AJAX Requests & Validation :
In this example, we used a traditional form to send data to the
application. However, many applications use AJAX requests. When using
the validate method during an AJAX request, Laravel will not generate
a redirect response. Instead, Laravel generates a JSON response
containing all of the validation errors. This JSON response will be
sent with a 422 HTTP status code.
So as you said : that means you don't need to put your ifs to handle validation laravel will take care of them itself great :)
here is some syntax that i use
public static $user_rule = array(
'user_id' => 'required',
'token' => 'required',
);
public static function user($data)
{
try{
$rules = User::$user_rule;
$validation = validator::make($data,$rules);
if($validation->passes())
{
}
else
{
return Response::json(array('success' => 0, 'msg'=> $validation->getMessageBag()->first()),200);
}
return 1;
}
catch(\Illuminate\Databas\QueryException $e) {
return Response::json(array('success' => 0, 'msg' => $e->getMessage()),200);
}
}
hope this will help you!
Please add Accept: application/json in you header.
Laravel automatically send an error message with response code.
As per 2019 Laravel 5.8 it is as easy as this:
// create the validator and make a validation here...
if ($validator->fails()) {
$fieldsWithErrorMessagesArray = $validator->messages()->get('*');
}
You will get the array of arrays of the fields' names and error messages.
You can show first error.
if ($validator->fails()) {
$error = $validator->errors()->first();
}
For all error :
$validator->errors()

Add a validation which is not related to the form

I want to add a validation on a form. My actual form works, here it is:
public function store(Request $request, $id)
{
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
]);
// Do something if everything is OK.
}
Now, I want to check if the user is "active" too. So something like:
\Auth::user()->isActive();
And return an error with the other validation errors if the user is not active.
Can I append something to the validator that has no relation with the form itself? I mean I want to add an error to the other errors if the user is not active.
That code is only validating the request variable (first argument of validate() function). So you will have to put someting in the request to validate it. It applies the rules to the object/array given.
$request->is_active = Auth::user()->isActive();
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
'is_active' => true //or whatever rule you want
]);
Anyways, I never tried that so not sure it will work. The usual way is to do an if
if ( !Auth::user()->isActive() ) {
return redirect->back()->withErrors(['account' => 'Your account is not active, please activate it']);
}
//continue here

Laravel Eloquent Create does nothing

So I'm learning Laravel, and I'm trying to create a new user in the database using data entered into a form. In my controller, I'm getting the form data fine, passing it to a validator with some rules which pass fine, but then when I try to create the User, nothing gets added to the database and it redirects to the basic "Whoops, looks like something went wrong." error page instead of the page I'm telling it to.
Here's my controller function:
public function doRegister() {
$rules = array(
'fname'=>'required|alpha|min:2',
'lname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'company'=>'required|alpha|min:2',
'password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()) {
User::create(array(
'fname' => Input::get('fname'),
'lname' => Input::get('lname'),
'email' => Input::get('email'),
'password' => Hash.make(Input::get('password')),
'company' => Input::get('company'),
'created_at' => date('Y-m-d H:m:s'),
'updated_at' => date('Y-m-d H:m:s')
));
return Redirect::to('login')->with('message', 'Thank you for registering!');
} else {
return Redirect::to('register')
->with('message', 'The following errors occurred')
->withErrors($validator)
->withInput(Input::except('password'));
}
}
Removing the User::create() section, the redirect works perfectly fine. Just to start with I've included all the database fields in the fillable array in my User model. Still doesn't work. Any ideas?
Not the direct answer to your question, but the quickest way for you to find it.
Open app.php
edit the last line seen in this picture from (in your case) false to true:
Once done that, laravel will tell you what the error is.
One error for sure is
'password' => Hash.make(Input::get('password')),
should be with ::
'password' => Hash::make(Input::get('password')),
You don't need this:
'created_at' => date('Y-m-d H:m:s'),
'updated_at' => date('Y-m-d H:m:s')
laravel will do this for you!
If it doesn't work after this, try to run
php artisan dump-autoload
from your terminal to generate an optimized class loader!

Categories