Email works with route using get request but email will not send with post request and there are no errors just a page refresh - laravel

I have verified emails are sending via mailgun with a public function mail using a get request with no data on the page. Trying to send an email from a contact page with a POST request simply refreshes the page with no errors but email does not send.
I have set the .env and config.mail / config.services and successfully send mail using a get request in web.php.
First I used Terminal php artisan make:mail. Then I created two routes for a contact page (GET / POST), created a contact view (works), send the data to PagesController.php, run a validation of the three inputs, pass the data to Mail::send. On click of submit button the page refreshes with no errors (validation not working) and email doesn't send.
PagesController.php:
Namespace(
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\Mail\Welcome;
use Mail;
class PagesController extends Controller
{
public function getContact(){
return view('pages/contact');
}
public function postContact(Request $request){
$this->validate($request,[
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min: 3'
]);
$data = array(
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
\Mail::send('email.Test', $data, function($message) use ($data){
$message->from($data['email']);
$message->to('visionquest.jesse#gmail.com');
$message->subject($data['subject']);
});
}
Web.php:
Route::get('contact', 'PagesController#getContact');
Route::post('contact', 'PagesController#postContact');
Test.blade.php:
<html>
<h1> Email from: {{ $email }}</h1>
<p> {{ $subject }} </p>
<br><br>
<hr>
<p>{{ $bodyMessage}}</p>
contact.blade.php:
#extends('main')
#section('title', '| Contact')
#section('content')
<div class="row">
<div class="col-md-12">
<h1>Contact Me</h1>
<hr>
<form acion="{{ url('contact') }}">
{{ csrf_field() }}
<div class="form-group">
<label name="email">Email:</label>
<input id="email" name="email" class="form-control">
</div>
<div class="form-group">
<label name="subject">Subject:</label>
<input id="subject" name="subject" class="form-control">
</div>
<div class="form-group">
<label name="message">Message:</label>
<textarea id="message" name="message" class="form- control">Type your message here...</textarea>
</div>
<input type="submit" value="Send message" class="btn btn-success">
</form>
</div>
</div>
#endsection
All I want to do is pull the information from the form and send it via email to a set address. I have been working on this for over week and now that I am not getting errors I have no idea what to do.

You can add this above the form in your blade file. You would be able to see the validation errors if any :
#if ($errors->any())
#foreach ($errors->all() as $error)
<div>{{$error}}</div>
#endforeach
#endif
Also change :
<form acion="{{ url('contact') }}">
To
<form action="{{ url('contact') }}" method="POST">

put some method on your form : method="POST" because once you will submit it, it will route to the GET route not the POST route since you did not declare a method on your form

Related

Laravel validate method does not prevent user from validating

I don't have any errors, nor on client or server. To give you more context I'm creating a login form, I'm trying to prevent the user from authenticate himself if the text he typed on the input fields are corrects. If it's not correct, the user should not be redirected to the route (which has the name "authenticate").
there are 3 routes: login and home which are pages, and authenticate that's redirecting to a controller which got all the functions related to the login.
AuthController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function login() {
return view('auth.login');
}
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required'
]);
}
}
Login view
<form action="{{ route('authenticate') }}" method="post">
#csrf
<input type="email" name="email">
<input type="password" name="password">
<button class="submit">Log</button>
</form>
All the routes
Route::get('home', HomeController::class)
->name('home');
Route::get('login', [AuthController::class, 'login'])
->name('login');
Route::get('authenticate', [AuthController::class, 'authenticate'])
->name('authenticate');
So basically what I'm trying to do is to check if the text the user has typed into the email field is an email, and if all the fields have text in it, because everything is required. But it seems like it's not the case, even if the fields are empty the log in button redirects to the authenticate page. Did I do something wrong? If I didn't provide enough information I would be glad to provide more, thanks for reading :) have a nice day
add required field to your input tag
#if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
{{Session::get('success')}}
</div>
#elseif(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
{{Session::get('failed')}}
</div>
#endif
<div class="form-group">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" class="form-control" value="{{old('email')}}" required />
{!!$errors->first("email", "<span class='text-danger'>:message</span>")!!}
</div>
Try this...

Form Won't Pass Value Pair In Get Request Url After Submission

I'm familiarizing myself with API's Get & Post Request in Laravel. I have a form where an admin can send Points to an external API. Unfortunately, in the documentation the request has to be a GET request and the data which is being submitted has to append to the url
ie: myurl.com/my-end-point?platform_id=value&auth=value...
The issue is, whenever i fill the form and submit the url remains the same:
ie: myurl.com/my-end-point?platform_id=platform_id&auth=auth...
It does not pass the data in the get request.
Controller
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => 'platform_id',
'auth' => 'auth',
'cpd_id' => 'cpd_id',
'registration_number' => 'registration_number',
'certificate' => 'certificate',
]);
dd($response);
}
View (Blade)
<form action="{{url('admin/rewards/points/manual_update/dashboard/store/participants-points') }}" method="POST">
<div class="modal-body">
{{ csrf_field() }}
<div class="form-group">
<label>Platform Id</label>
<input type="text" name="platform_id" id='platform_id' class="form-control" value="123" readonly>
</div>
<div class="form-group">
<label>Authentication Key</label>
<input type="text" name="auth" id='auth' class="form-control" value="123456789" readonly>
</div>
<div class="form-group">
<label>Cpd Id</label>
<input type="text" name="cpd_id" id='cpd_id' class="form-control" placeholder=".ie 587">
</div>
<div class="form-group">
<label>Registration Number</label>
<input type="text" name="registration_number" id='registration_number' class="form-control" placeholder=".ie MDC/PA/RNXXXX">
</div>
<div class="form-group">
<label>Certificate Serial Number</label>
<input type="text" name="certificate" id='certificate' class="form-control" placeholder=".ie 2022-03/001">
</div>
<button type="send" class="btn btn-primary">Send</button>
</div>
</form>
Help is greatly appreciated. As i really want to get better.
You need to pass the value from the form . You can use $request-> from the request facade
You can try this
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
'platform_id' => $request->platform_id,
'auth' => $request->auth,
'cpd_id' => $request->cpd_id,
'registration_number' => $request->registration_number,
'certificate' => $request->certificate,
]);
dd($response);
}
Let me see if I understand. Does your backend that handles the request call an external API? If that's the case, the problem is that you're passing strings as an argument. To retrieve the form values try something like:
$request->auth or
$request->get('auth')
If this is not the case, and you simply want to get the form data in your backend, I advise you to do it with JS using AJAX. You can use Fetch or install an external lib like axios to do this.
NOTE: the type of your submit button is incorrect, change it to type="submit"
https://www.w3schools.com/tags/att_button_type.asp

Send email and get reply in laravel form

I'm succeed to send mail from contact form, and now my requirement is to get automated success reply to the users input email address when submitting the form. please help me on this
ContactUsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactUs;
class ContactUsController extends Controller
{
function index()
{
return view('home/contactus');
}
function send(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'message' => 'required'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'subject' => $request->subject,
'message' => $request->message
);
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
return back()->with('success', 'Thanks for contacting us! We will get back to you soon.');
}
}
ContactUs
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ContactUs extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->from('xxxx#mail.com')
->subject('Customer Feedback')
->view('dynamic_email_template')
->with('data', $this->data);
}
}
Form
<div class="form">
<h4>Send us a message</h4>
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data- dismiss="alert">×</button>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data- dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
<form method="post" action="{{url('contactus/send')}}" autocomplete="off">
{{ csrf_field() }}
<div class="form-group">
<input type="text" name="name" for="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" for="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" for="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" for="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center">
<button type="submit" name="send" title="Send Message">Send Message</button>
</div>
</form>
</div>
dynamic_email_template
<p>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</p> </br>
<p>{{ $data['subject'] }}</p> </br>
<p>I have some query like "{{ $data['message'] }}".</p> </br>
<p>It would be appriciative, if you gone through this feedback.</p>
You need to create email template same like your view file, lets say contact_us_email.blade.php. In this file add this content
contact_us_email.blade.php
<html>
<body>
<h2>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Subject: {{ $data['subject'] }}</p> <br>
<p>I have some query like <b>"{{ $data['message'] }}"</b>. <br>
<p>It would be appriciative, if you gone through this feedback.</p>
</body>
</html>
NOTE: Add css or styling according to your need. this is basic html
Edit: To send confirmation email to user
For success confirmation to user, you can create another email template like
contact_us_thank_you_email.blade.php
<html>
<body>
<h2>Hello, {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Thank You for your interest...blah blah blah</p> <br>
<p>Our team will contact you soon</p> <br>
</body>
</html>
Now in your ContactUsController, replace
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
with
Mail::send('contact_us_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to('xxx#mail.com')->subject($data['subject']);
});
Mail::send('contact_us_thank_you_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to($data['email'])->subject('Thank you for the interest');
});
And I think you are good to go with this. I hope this is what you are asking for.

Laravel Form validation redirects back to home page upon form errors instead of staying on same page

I have a contact form that when submitted, is successfully going to the DB. The issue is, when I check for validation on my webpage, the errors appear properly using Larvael $error validation, the problem is that my webpage always redirects back to home when errors show up instead of the page remaining still and showing the errors. I have to keep scrolling down to where my contact form is to see the errors; this will be annoying for my future users. How do I get the page to remain where it is if there are errors? NOTE: My page redirects correctly when the form is valid and submitted, this is not an issue. NOTE-2: I have created a single page webpage that the nav-links take you to, there are no redirects. Instead, it is one HTML page.
Web.php
Route::get('/', 'HomeController#index')->name('home');
Route::post('/contact/submit', 'MessagesController#submit');
MessagesController.php
namespace App\Http\Controllers;
use App\Message;
use Illuminate\Http\Request;
class MessagesController extends Controller
{
public function submit(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
Message::create($validatedData);
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
}
contact.blade.php
{{--CONTACT FORM--}}
<section id="contact">
<div class="container-fluid padding">
<div class="row text-center padding">
<div class="col-12">
<h2 class="lead display-3">Contact Us</h2>
<hr class="my-4">
<form action="/contact/submit" method="POST">
#csrf
<div class="field">
<label for="name" class="label">Name</label>
<div class="control">
<input type="text" class="input {{$errors->has('name') ? 'is-danger' : 'is-success'}}"
name="name" placeholder="Project Title" value="{{old('name')}}">
</div>
</div>
<div class="field">
<label for="name" class="label">Email</label>
<div class="control">
<input type="text" class="input {{$errors->has('email') ? 'is-danger' : 'is-success'}}"
name="email" placeholder="Project Title" value="{{old('email')}}">
</div>
</div>
<div class="field">
<label for="name" class="label">Phone Number</label>
<div class="control">
<input type="text"
class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
name="phonenumber" placeholder="Project Title" value="{{old('phonenumber')}}">
</div>
</div>
<div class="field">
<label for="message" class="label">Message</label>
<div class="control">
<textarea name="message"
class="textarea {{$errors->has('message') ? 'is-danger' : 'is-success'}}"
placeholder="Project description">{{old('message')}}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
<!--Errors variable used from form validation -->
#if($errors->any())
<div class="notification is-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</form>
</div>
</div>
</div>
</section>
You need to create a manual validator so that you have control over the redirect if the validation fails (which I assume is what you are having issues with).
public function submit(Request $request)
{
$validator = Validator::make($request->all(),[
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
if ($validator->fails()) {
return redirect(url()->previous() .'#contact')
->withErrors($validator)
->withInput();
}
Message::create($request->all());
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
First, move the errors to the top of the form so you can see them.
<form action="/contact/submit" method="POST">
#csrf
#if($errors->any())
<div class="notification is-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
A better way of handling validation is to separate it using a form request.
php artisan make:request SendMessageRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendMessageRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
];
}
}
If validation fails, a redirect response will be automatically generated to send the user back to their previous location.
Now update your controller.
use App\Http\Requests\SendMessageRequest;
use App\Message;
class MessagesController extends Controller
{
public function submit(SendMessageRequest $request)
{
Message::create($request->validated());
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
}
You can leave the validation in your controller using the Validator and back() redirection, but the first is the better way.
public function submit(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
if ($validator->fails()) {
return back()->withInput()->withErrors($validator);
}
Message::create($request->all());
return redirect('/')->with('success,' 'Your message has been
successfully sent. We will reach out to you soon');
}

Laravel undefined variable in view, Laravel 5.2 using AdminLTE

I am getting an error in laravel 5.2
when I access it using the storeMessage function on my Controller
This is my ERROR STATEMENT:
ErrorException in 6e12af76911d23528f6e0ea587ccab13391eacf9.php line 37:
Undefined variable: thisPage (View: E:\xampp\htdocs\beasiswa\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\beasiswa\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\beasiswa\resources\views\layouts\partials\sidebar.blade.php)
And this is my code:
View Code
<?php $thisPage = "jenisbeasiswa"; ?>
#extends('layouts.app')
#section('htmlheader_title')
Portal Beasiswa
#endsection
#section('contentheader_title')
Broadcast Beasiswa via Telegram Messenger
#endsection
#section('main-content')
<form action="{{ url('/send-message') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" id="message" class="form-control" placeholder="Enter your query" rows="10"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
#endsection
and this is my Controller Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Telegram\Bot\FileUpload\InputFile;
use Telegram\Bot\Laravel\Facades\Telegram;
class TelegramBotController extends Controller
{
public function updatedActivity()
{
$activity = Telegram::getUpdates();
dd($activity);
}
public function sendMessage()
{
return view('beasiswa.telegram');
}
public function storeMessage(Request $request)
{
$request->validate([
'email' => 'required|email',
'message' => 'required'
]);
$text = "[HEADLINE] Informasi Portal Beasiswa\n"
. "<b>Email Address: </b>\n"
. "$request->email\n"
. "<b>Message: </b>\n"
. $request->message;
Telegram::sendMessage([
'chat_id' => env('TELEGRAM_CHANNEL_ID', ''),
'parse_mode' => 'HTML',
'text' => $text
]);
return redirect()->back();
}
}
Apparently sidebar.blade.php is referring to the $thisPage variable (which is declared at the top of your view code). My guess is, you are including the sidebar in the layouts.app template. But as you extend your layouts.app the $thisPage variable will get rendered in the sidebar first before the declaration comes in your view code. And thus, it will be undefined in the Sidebar.
So, you should try another approach. Why do you even want to set the $thisPage variable? Maybe you can pass it in from the controller?

Resources