I have a controller that validates some input and when validation fails it passes the errors to my view:
public function updateAccount(){
$user = Auth::user();
$validation = User::validateAccount(Input::all());
if( $validation->passes() ){
$user->fill(Input::all());
$user->save();
return Redirect::back();
} else {
return Redirect::back()
->withErrors($validation)
->withInput();
}
}
The code for User::validateAccount(); looks like this:
public static function validateAccount($input){
$rules = [
'website' => 'url'
];
$validation = Validator::make($input, $rules);
return $validation;
}
In my view I display the errors like this:
#if($errors->any())
<div class="errors">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
However, instead of the default, user friendly error output I get this. For a URL validation error it displays:
validation.url
How do I get Laravel to display the default, user friendly error messages that are configured in app/lang/en/validation.php?
So for a URL error this should be:
"The :attribute format is invalid."
You need to define the custom message.
Change
public static function validateAccount($input){
$rules = [
'website' => 'url'
];
$validation = Validator::make($input, $rules);
return $validation;
}
to
public static function validateAccount($input){
$messages = [ 'url' => 'You must give a valid url'];
$rules = [ 'website' => 'url' ];
$validation = Validator::make($input, $rules, $messages);
return $validation;
}
OR
You can add this to your app/lang/en/validation.php file:
'custom' => array(
'website' => array(
'url' => 'You must give a valid url',
),
),
Related
I've got a form in Codeigniter 4 and I'm using the form helpers to build the form.
When I use a form_input I can reload the submitted values of the form using the old() method. Like below.
<span class="input-group-text" id="inputGroup-sizing-sm">Membership Number</span>
<?php
$current_membership_options = [
'id' => "membership_number",
'name' => "membership_number",
'class' => "form-control",
'type' => 'text'
];
echo form_input($current_membership_options, old('membership_number'))
?>
I've tried a couple of different options but I can't get it to repopulate with a form_dropdown.
THE VIEW
<span class="input-group-text" id="inputGroup-sizing-sm">Membership Type</span>
<?php
$membership_type_option = [
'id' => 'membership_type',
'name=' => 'membership_type',
'class' => 'form-select ',
'type' => 'text'
];
echo form_dropdown($membership_type_option, $membership_type, old('membership_type'));
?>
I get $membership_type from the user controller.
public function new(): string
{
$user = new User;
$data = $this->model->getMemberships();
return view('Admin/Users/new', [
'user' => $user,
'membership_type' => $data
]);
}
And the model
/**
* #throws Exception
*/
public function getMemberships(): array
{
$result = $this->db->query('select * from membership_type')->getResultArray();
$dropdown = array();
$dropdown['0'] = 'Please Select';
foreach ($result as $r)
{
$dropdown[$r['id']] = $r['type'];
}
return $dropdown;
}
Thanks in advance.
I have configured a resource route as below
Route::resource('users', UserController::class);
When a user posts data, it will call the store method in the controller where it will add the data and set a message for success/failure.
public function store(Request $request)
{
// return $request;
$request->validate(
[
"firstName" => 'required',
"lastName" => 'required',
"phoneNo" => 'required',
"email" => 'email:rfc,dns'
]
);
$date = date(now());
$data = [
'firstName' => $request->firstName,
'lastName' => $request->lastName,
'phoneNo' => $request->phoneNo,
'email' => $request->email,
'designation' => $request->designation,
'status' => $request->status,
'createdAt' => $date,
'updatedAt' => $date,
];
$user = Firebase::insertData($data, static::$collection);
if ($user->id() != null) {
$message = "User Created Successfully";
} else {
$message = "Something went wrong. Please contact System Admin with error code USR001";
}
return redirect()->route('users.index', ['message' => $message]);
}
This will redirect to the index method of the same controller. How can I use the $message parameter in the index method and send it to the view? My index method is below
public function index()
{
$userCollection = app('firebase.firestore')->database()->collection('users');
$userData = $userCollection->documents();
$response = [];
$app = app();
foreach ($userData as $data) {
$user = $app->make('stdClass');
$user->firstName = $data["firstName"];
$user->lastName = $data["lastName"];
$user->phoneNo = $data["phoneNo"];
$user->email = $data["email"];
$user->designation = $data["designation"];
$user->status = $data["status"];
$user->createdAt = $data["createdAt"];
$user->updatedAt = $data["updatedAt"];
array_push($response, $user);
}
return view('pages.user.list-user', ['response' => $response]);
}
You can directly pass the message as a flash message using the with() method with the redirect method.
Edit your redirect code as:
return redirect()->route('users.index')->with('message', $message]);
and add the below code in your pages.user.list-user blade file:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
Visit https://laravel.com/docs/8.x/redirects#redirecting-with-flashed-session-data for more info on redirects with a flash message.
Replace your redirect code :
return redirect()->route('users.index', ['message' => $message]);
with
return view('pages.user.list-user', ['message' => $message]);
(1) First of all, pass the message in the parameter of index function:
public function index($message)
{
...
}
(2) This is okay, you wrote correctly:
return redirect()->route('users.index', ['message' => $message]);
(3) Now just access the message in the view (blade) and print it:
{{ $message }}
You can also store message in $response array and simply pass the $response to the desired view:
$response['message'] = $message;
You can have the index method like if the parameter used in the controller.
public function index(Request $request)
{
// Your code
$message = $request['message'];
}
If you want to access the message in view use
return redirect()->route('users.index')->with('message', $message]);
and access from the view using session('message') like in OMi Shah's answer
i am trying to first set in controller setOption(value, valuename) in controller and store in database and use it as getOption in views
but not working .
Here is my controller =>
public function edit(Request $request)
{
mpc_m_c($request->server('SERVER_NAME'));
$options = Config::all()->pluck('value','name');
$tzlist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
return view('admin.system-settings', compact('options', 'tzlist'));
}
public function update(Request $request)
{
$this->validate($request, [
'app_name' => 'required',
'currency_symbol' => 'required',
'currency_code' => 'required',
'date_format' => 'required',
'home_page_description' => 'required',
'recaptcha_private_key' => 'required',
'minimum_deposit_amount' => 'required',
'home_page_meta' => 'required',
'notify_email' => 'required'
]);
if ($request->hasFile('logo')) {
$file = $request->file('logo');
$fileArray = array('logo' => $file);
$rules = array(
'logo' => 'mimes:png|required|' // max 10000kb
);
$validator = Validator::make($fileArray, $rules);
if ($validator->fails()) {
$errors = $validator->errors()->getMessages();
return redirect()
->back()
->withErrors(['logo' => $errors['logo']]);
} else {
$logo = Storage::putFile('images', $request->file('logo'));
setOption('logo', $logo);
}
}
if ($request->hasFile('banner')) {
$file = $request->file('banner');
$fileArray = array('banner' => $file);
$rules = array(
'banner' => 'mimes:png,jpg,jpeg|required|' // max 10000kb
);
$validator = Validator::make($fileArray, $rules);
if ($validator->fails()) {
$errors = $validator->errors()->getMessages();
return redirect()
->back()
->withErrors(['banner' => $errors['banner']]);
} else {
$banner = Storage::putFile('images', $request->file('banner'));
setOption('banner', $banner);
}
}
setOption('app_name', $request->input('app_name'));
setOption('currency_symbol', $request->input('currency_symbol'));
setOption('currency_code', $request->input('currency_code'));
setOption('date_format', $request->input('date_format'));
setOption('home_page_description', $request->input('home_page_description'));
setOption('recaptcha_public_key', $request->input('recaptcha_public_key'));
setOption('recaptcha_private_key', $request->input('recaptcha_private_key'));
setOption('minimum_deposit_amount', $request->input('minimum_deposit_amount'));
setOption('home_page_meta', $request->input('home_page_meta'));
setOption('module_support_enabled', $request->input('module_support_enabled'));
setOption('module_api_enabled', $request->input('module_api_enabled'));
setOption('module_subscription_enabled', $request->input('module_subscription_enabled'));
setOption('theme_color', $request->input('theme_color'));
setOption('background_color', $request->input('background_color'));
setOption('language', $request->input('language'));
setOption('display_price_per', $request->input('display_price_per'));
setOption('admin_layout', $request->input('admin_layout'));
setOption('user_layout', $request->input('user_layout'));
setOption('panel_theme', $request->input('panel_theme'));
setOption('anonymizer', $request->input('anonymizer'));
setOption('front_page', $request->input('front_page'));
setOption('show_service_list_without_login', $request->input('show_service_list_without_login'));
setOption('notify_email', $request->input('notify_email'));
setOption('currency_separator', $request->input('currency_separator'));
setOption('timezone', $request->input('timezone'));
Session::flash('alert', __('messages.updated_logout_needed'));
Session::flash('alertClass', 'success');
return redirect('/admin/system/settings');
}
route =>
Route::get('/system/settings', 'ConfigController#edit');
Route::put('/system/settings', 'ConfigController#update');
error =>
"Call to undefined function App\Http\Controllers\Admin\setOption()"
and view =>
<div class="form-group{{ $errors->has('home_page_meta') ? ' has-error' : '' }}">
<label for="home_page_meta" class="control-label">meta tags</label>
<textarea
style="height: 150px;"
class="form-control"
data-validation="required"
rows="5"
id="home_page_meta"
name="home_page_meta"> <?php echo e($options['home_page_meta']) ?></textarea>
</div>
use =>
getOption('valuename')
And by this things he is using the function getOption(''valuename) anywhere in the entire application ... i really dont want use it but just curious How he is using this things even there's no laravel build in funtion for this name?
*Note : Please don't judge me , I just want to know ..thnaks
anybody got idea how do i use it ?
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;
I'm making a contact form with laravel 5.4 and I want to get an email when someone sends the contact form. I'm using Mailtrap to receive emails.
The problem I'm getting is that I get this error when I submit the form.
ErrorException in helpers.php line 533:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\xampp\htdocs\website\app\Modules\Templates\Resources\Views\emails\contact.blade.php)
My contact function
public function contact()
{
$data = Input::all();
$rules = array(
'name' => '',
'email' => '',
'message' => '',
);
$validator = Validator::make($data, $rules);
if($validator->passes())
{
Mail::send('templates::emails.contact', $data, function($message){
$message->from(Input::get('email'), Input::get('name'));
$message->to('info#site.com', 'Info')->subject('Testing contact form');
});
Session::flash('success', 'Your message has been sent successfully.');
return back();
}else{
return back()->withErrors($validator);
}
}
and my contact.blade.php that is the information that gets sent to me
<h1>We been contacted by.... </h1>
{{ $name }}<br />
{{ $email }}<br />
{{ $subject }}<br />
{{ $message }}<br />
You're passing the $data which holds the array of input. You need to access them like shown below.
Change the data being passed to
Mail::send('templates::emails.contact', compact('data'), function($message)
Change your view code to
{{ $data['name'] }}<br/>
{{ $data['email'] }}<br/>
{{ $data['message'] }}<br/>
You're also trying to access subject in the view when isn't available in the input.
you need to Add $subject in ur cantact function or remove it from cantact.blade.php, try this code :
public function contact()
{
$cdata = Input::all();
$crules = array(
'name' => '',
'email' => '',
'subject' => '',
'message' => '',
);
$validator = Validator::make($cdata, $crules);
if($validator->passes())
{
Mail::send('templates::emails.contact', $cdata, function($message){
$message->from(Input::get('email'), Input::get('name'));
$message->to('info#site.com', 'Info')->subject('Testing contact form');
});
Session::flash('success', 'Your message has been sent successfully.');
return back();
}else{
return back()->withErrors($validator);
}
}
and some times u got an error because ur variables have the same name of stored variables ( like data,timer,for ... etc)