This is the code i use to send an email with a contact form:
my route:
Route::post('/contatti/mail','ItemController#mail');
my controller
public function mail()
{
$data = Input::all();
$rules = array(
'subject' => 'required',
'message' => 'required'
);
$validator = Validator::make($data, $rules);
if($validator->fails()) return Redirect::to('contatti')->withErrors($validator)->withInput();
$emailcontent = array (
'subject' => $data['subject'],
'emailmessage' => $data['message']
);
Mail::send('emails.contactmail', $emailcontent, function($message){
$message->to('mymail#mymail','')->subject('Contatti');
return Redirect::to('contatti')->with('flash_message', 'Mail sent');
}
}
Why this sintax is wrong? I mean, i can't nest function in a controller in laravel?
How can i do to send the mail? I should use the post and send to a route called Mail::send with that call another controller with that parameter?
EDIT: This is the error i get:
Symfony \ Component \ Debug \ Exception \ FatalErrorException
syntax error, unexpected '}'
its a syntax error
close closure function parentheses
Mail::send('emails.contactmail', $emailcontent, function($message){$message->to('mymail#mymail','')->subject('Contatti'); });
Related
I have already asked question about Laravel 5.7 validation, however it still does not work quite right. the validation is not executed at all when sending the content.
public function store(Request $request)
{
$data=$request->all();
$validator = Validator::make($data, [
'first_name' => 'alpha|min:2|max:30',
]);
}
Thanks in advance
if your are not using form validation then maybe it will be helpful for you.
I add validator example in your code, you can try it
maybe your problem will resolve
public function update(Request $request, Player $player)
{
//example validation
$validator = Validator::make($request->all(), [
'id' => 'required|integer', //put your fields
'text' => 'required|string' //put your fields
]);
if ($validator->fails()){
return "Invalid Data";
}
if(Auth::check()){
$playerUpdate = Player::where('id', $player->id)
->update([
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name')
]);
if($playerUpdate){
return redirect()->route('players.show', ['player'=> $player->id])
->with('success' , 'player foo');
}
}
return back()->withInput()->with('errors', 'Foo error');
}
I don't see your validation code at all.
there are two ways for implementing the validation in laravel
Form Request Validation
validation in controller methods
Please Add one, and try again
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;
ERROR
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, string given, called in mypath\app\Http\Controllers\PostsController.php on line 65
Controller
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'image' => 'mimes:jpeg,png,jpg,gif,svg|max:2048',
'body' => 'required'
]);
//dd($request);
auth()->user()->publish(
Storage::putFile('images', new File($request['image']), 'public'),
new Post(request('title', 'image', 'body'))
);
session()->flash('message', 'your post has now been published');
return redirect('/');
}
......
You need to give request parameters to create new post in array format like this,
$request->only('title', 'image', 'body')
So that your code looks like,
auth()->user()->publish(
Storage::putFile('images', new File($request['image']), 'public'),
Post::create($request->only('title', 'image', 'body')))
);
I hope you will understand.
My route
Route::put('/users/{$id}', 'ApiController#profileUpdate')->name('user.update');
//profile update function
public function profileUpdate(Request $request){
try{
$validator = $this->validatorProfile($request->all());
if ($validator->fails()) {
$messages = $validator->messages();
return response()->json([
'status' => 400,
'error' => true,
'result' => false ,
'message'=> $messages,
'data' => []
]);
}
$id = $request->id;
$token = $request->header('authorization');
$user_id = JWTAuth::toUser($token)->id;
$user = User::find($user_id);
$data = $request->only('location','state','country','name');
$result = $user->profiles()->where(['user_id' => $$id])->update([
'location' => $data['location'],
'state' => $data['state'],
'country' => $data['country'],
]);
$result1 = $user->where(['id' => $user_id])->update([
'name' => $data['name'],
]);
return response()->json([
'status' => 200,
'error' => false,
'result' => true,
'message'=> "profile updated",
'data' => $data
]);
}
catch(Exception $e){
return response()->json([
'status' => 400,
'error' => true,
'result' => false,
'message'=> $e,
'data' => []
]);
dd($e);
}
}
Help me to find my mistake.
My url
http://localhost/project/public/api/v1/users/1
When i hit it on postman it give 404 error.
You will have to adjust your route parameter choice of naming. {$id} isn't going to work, but {id} will work just fine. Also the $$id reference in the code probably should be just $id.
As Alexey Mezenin has pointed out, it additionally would be good to add the $id parameter to your controller method to accept the route parameter.
Side Note:
When you are calling $request->id you are probably trying to get the route parameter, but that may not always return that. If there is any input in the Request named id that will be returned before a route parameter named id. It only tries to return a route parameter as a fallback.
$request->input('id') explicitly ask for an input named id.
$request->route('id') explicitly ask for a route parameter named id.
$request->id could be an input named id or a route parameter named id.
Since you're trying to pass ID, you need to add it as an argument. So, change this:
public function profileUpdate(Request $request)
To:
public function profileUpdate(Request $request, $id)
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
}
});
}