I am working on building a form in which I want to populate the fields coming from form (which I have named posting.blade.php)
The controller which I have used for that is:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'number' => 'required',
'city' => 'required',
'post' => 'required'
]);
Mail::send('emails.posting-message', [
'msg'=> $request->message
], function($mail) use($request) {
$mail->from($request->email, $request->name);
$mail->to('helloworld#gmail.com')->subject('Contact Message');
});
return redirect()->back()->with('flash_message', 'Thank you for your message');
}
Problem Statement:
The current controller doesn't return anything as in the line 'msg'=> $request->message there is no message in validate. But if I use
'msg'=> $request->name (It returns name)
I am wondering what changes I should make in the controller so that it return every field present in the validate.
I tried with this but its only returning the last value which is post.
'msg'=> $request->name,
'msg'=> $request->email,
'msg'=> $request->number,
'msg'=> $request->city,
'msg'=> $request->post
First, you need to add ->withInput() to your redirect:
return redirect()->back()->with('flash_message', 'Thank you for your message')->withInput();
This will flash all submitted form fields to the session.
After the redirect, to get the value of a form field with the name of title for example, you can use the old() helper, such as:
<input type="text" name="title" value="{{ old('title') }}">
You can also pass a second parameter to the helper:
<input type="text" name="title" value="{{ old('title', $post->title) }}">
You get the idea.
It sounds like what you are trying to do is take all of the inputs from a form submission and pass them to a Laravel blade template called posting-message that is being used to build an email.
If my understanding is correct, then you are almost there - this just requires you to pass more variables through to your email blade template. At the moment, you are just passing through one variable called msg.
So the Mail section of your controller becomes something like:
Mail::send('emails.posting-message', [
'name'=> $request->name,
'email'=> $request->email,
'number'=> $request->number,
'city'=> $request->city,
'post'=> $request->post
], function($mail) use($request) {
$mail->from($request->email, $request->name);
$mail->to('helloworld#gmail.com')->subject('Contact Message');
});
Then in your email blade template you have access to the variables like {{ $name }}, {{ $email }} and so on.
p.s.
If you wanted to get all the inputs and put them in an array in one go in your controller, Laravel provides some ways of retrieving inputs in bulk, e.g.:
$allInputs = $request->all();
p.p.s. Consider doing more validation than just required for each of your form inputs, to ensure the data supplied from your user is what you are expecting and not malicious or incorrect.
First thing you need to check the field name in your html that its exact message no spaces or sort of misspelled.
Second thing Check all the post fields using
$request->all(); And see whether you get the "message" index in the post array or not.
There is nothing like if you have not added the field in the validation so you will not get it in the POST.
But as you are working with contact form you should keep the "message" field mandatory and should add it in validation. That way you will always get some data in the message field.
Can you please post the html also in the question so everyone will get more idea about it.
For the other issue about sending the data you already getting to the mail template you can use the below approach
$msg = array('name' => $request->name,'email' => $request->email,'number' => $request->number,'city' => $request->city,'post' => $request->post,'message'=>$request->message);
You can than use the array like
Mail::send('emails.posting-message', [$msg
], function($mail) use($request) {
$mail->from($request->email, $request->name);
$mail->to('helloworld#gmail.com')->subject('Contact Message');
});
Then you can easily access all the variables in the mail template to make it dynamic.
The snippet you have provided as below:
'msg'=> $request->name,
'msg'=> $request->email,
'msg'=> $request->number,
'msg'=> $request->city,
'msg'=> $request->post
Indicates that the array key msg is being overwritten 4 times.
You would want the following approach instead:
$msg['name'] = $request->name;
$msg['email'] = $request->email;
$msg['number'] = $request->number;
$msg['city'] = $request->city;
$msg['post'] = $request->post;
First of all, you don't need to use the back method with redirect, back() function will redirect users anyway.
return back()->with('key','Val');
Check this out: Old Input
As others said, To send query strings/Inputs to the cookies use withInput() function according to the documantions it will flash all current inputs:
return back()->with('key','Val')->withInput();
If you had seen Laravel's default register and login blades, You would have known that you could use old() helper to get previous values based on cookies and sessions.
'msg'=> $request->name,
'msg'=> $request->email,
'msg'=> $request->number,
'msg'=> $request->city,
'msg'=> $request->post
To assign a value to an array there are some ways, But remember never override them like this!
You could use the auto indexing method, If you use $msg[] = $request->bar, It will index values from 0 to the length of your assignments
$data[] = $request->val1;
$data[] = $request->val2;
...
But also you could determine each element's key like this:
$data['name'] = $request->name;
$data['email'] = $request->email;
...
After all, if you want to send all Inputs as second paramter just use $request->all():
Mail::send('emails.posting-message', $request->all(), function($mail) use($request) {
$mail->from($request->email, $request->name);
$mail->to('helloworld#gmail.com')->subject('Contact Message');
});
I have face similar problem some time ago, and after several tries I changed fieldname from message to comments and it was the solution.
I suspect that message maybe a variable name used by the framework in sessions or something like that.
I hope it helps.
yo need to add the withInput() method in your returned response as
return redirect()->back()->with('flash_message', 'Thank you for your message')->withInput();
to keep input from one request during the next request you need to use old() helper. Check the documention here https://laravel.com/docs/5.6/requests#old-input
<input type="text" name="title" value="{{ old('username') }}">
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.Check the docs here https://laravel.com/docs/5.6/validation#quick-displaying-the-validation-errors. To display validation error message you can use like this
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
or more specifically
<input type="text" name="title" value="{{ old('username') }}">
<span class="error">{{$error->title}}</span>
As i understand it, you're asking how to send the inputs to the mail template.
try this;
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'number' => 'required',
'city' => 'required',
'post' => 'required'
]);
Mail::send('emails.posting-message', $request->all(), function($mail) use($request) {
$mail->from($request->email, $request->name);
$mail->to('helloworld#gmail.com')->subject('Contact Message');
});
return redirect()->back()->with('flash_message', 'Thank you for your message');
}
now in the emails/posting-message.blade.php you will have access to $name, $email, $number, $city, $post and any other input you sent in the request.
now if you want to recover the errors of the validation. use this
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
//you can get the errors with $validator->errors. and redirect/mail as you want.
}
//here the inputs are valid.
Related
I am getting this error when i sent a post request to my resource controller. My controller code is
public function store(Request $request)
{
//return $request->all(); (here i am checking values sometimes showing values and sometimes showing the mac error.)
$tags = $request->input('tags');
if(!empty($tags)){
$tags = implode(",", $tags);
}
//return $request->from;
$status = FamousPost::create([
'name' => $request->input('from'),
'to_name' => $request->input('to'),
'title' => $request->input('title'),
'content' => $request->input('content'),
'avatar' => $request->input('from_avatar'),
'to_avatar' => $request->input('to_avatar'),
'tags' => $tags
]);
if($status)
return json_encode(true);
else
return json_encode(false);
}
Sometimes values are coming from request and sometimes(mostly) i am getting the MAC error. My frontend is angularjs i am submitting the form using $http service of angularjs.
Please check your .env file. There should be space between APP_KEY and APP_DEBUG
<input type="hidden" name="_token" value="{{ csrf_token() }} "/>
add this field in your form
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'],
]));
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
I can't seem to save the updated profile to the database.
In my edit.blade.php:
{!! Form::model($user, ['method' => 'PATCH', 'route' => ['profile.update', $user->company_name] ]) !!}
// fields
{!! Form::submit('Update Profile', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
In my ProfilesController:
public function update($company_name)
{
$user = User::whereCompanyName($company_name)->firstOrFail();
$user->save(); // no validation implemented
flash('You have successfully edited your profile');
return redirect('/');
}
After hitting the update button, it shows the flash message on the homepage but the it's not saving to the database. Im coming from Rails and I feel I need to whitelist something.
The point is, you don't change your user model at all... You retrieve it, and then save it again without setting any fields.
$user = User::whereCompanyName($company_name)->firstOrFail();
// this 'fills' the user model with all fields of the Input that are fillable
$user->fill(\Input::all());
$user->save(); // no validation implemented
If you are using the above method with
$user->fill(\Input::all());
you have to add a $fillable array to your User Model like
protected $fillable = ['name', 'email', 'password']; // add the fields you need
If you explicitly want to set only one or two ( or three....) field you could just update them with
$user->email = \Input::get('email'); // email is just an example....
$user->name = \Input::get('name'); // just an example...
...
$user->save();
If you have tried the anwer Sinmok provided, you probably get the "whooops" page because you used
Input::get('field');
instead of
\Input::get('field');
On your Blade Syntax i assume you use laravel 5.
So as your controller is namespaced you have to add a \ before Input to reference the root namespace ( or put a use statement on top of your class)
Generally on your development server you should enable debugging. Then you have more detailed information about what's going wrong than just the pure.. "whoops... "
In your config/app.php file you can set
'debug' => true;
OR
you have a look at http://laravel.com/docs/5.0/configuration
And use the .env file.
If you use the .env file make sure there is an entry with something like
APP_DEBUG=true
then you can access that value in your config/app.php with
'debug' => env('APP_DEBUG'),
There should be a .env.example in your installation to give you a clue how such a file could look like.
UserController update function look like that :-
public function update(Request $request)
{
$user = Auth::user();
$data = $this->validate($request, [
'name' => 'required',
'email' => 'required',
]);
$user->name = $data['name'];
$user->email = $data['email'];
$user->save();
return redirect('/user_edit/'.Auth::user()->id)->with('success', 'User has been updated!!');
}
Looks like you've not set the submission values to the user object.
Try (Update this is for Laravel 4)
$user = User::whereCompanyName($company_name)->firstOrFail();
$user->field = Input::get("some_field"); // Name of the input field here
$user->save(); // no validation implemented
flash('You have successfully edited your profile');
return redirect('/');
EDIT
Actually, if you're using Laravel 5 it looks like it should be:
$user->field = Request::input('some_field'); // Name of the input field here
$user->save(); // no validation implementedenter code here
I am trying to validate an update user profile form, whereby the validation should check that the email doesn't exist already, but disregard if the users existing email remains.
However, this continues to return validation error message 'This email has already been taken'.
I'm really unsure where I'm going wrong. Otherwise, the update form works and updates perfectly.
HTML
{{ Form::text('email', Input::old('email', $user->email), array('id' => 'email', 'placeholder' => 'email', 'class' => 'form-control')) }}
Route
Route::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController#update'));
User Model
'email' => 'unique:users,email,{{{ $id }}}'
Your rule is written correctly in order to ignore a specific id, however, you'll need to update the value of {{{ $id }}} in your unique rule before attempting the validation.
I'm not necessarily a big fan of this method, but assuming your rules are a static attribute on the User object, you can create a static method that will hydrate and return the rules with the correct values.
class User extends Eloquent {
public static $rules = array(
'email' => 'unique:users,email,%1$s'
);
public static function getRules($id = 'NULL') {
$rules = self::$rules;
$rules['email'] = sprintf($rules['email'], $id);
return $rules;
}
}
You can accomplish this with the sometimes function of the validator
Something like:
$validator->sometimes('email', 'unique:users,email', function ($input) {
return $input->email == Input::get('email');
});
See http://laravel.com/docs/4.2/validation#conditionally-adding-rules for more info