Laravel send email on form submit - php

So I have a simple form and I want whenever a user submits the form it to email me, not sure what the problem is as whenever I submit the form I'm getting a 500 error and I'm not sure why.
Here is the form:
<div class="contact" id="contact">
<form action="{{url('/contact')}}" method="post">
{{ csrf_field() }}
<input type="text" class="fname" name="firstname" placeholder="First Name">
<input type="text" class="lname" name="lastname" placeholder="Last Name">
<input type="text" class="address" name="address" placeholder="Address">
<input type="text" class="email" name="email" placeholder="Email">
<textarea id="subject" name="message" placeholder="Message" style="height:200px"></textarea>
<label class="checkbox-label">
<input type="checkbox" class="yard" name="yard"> I Want a Yard Sign
</label>
<br>
<label class="checkbox-label">
<input type="checkbox" class="host" name="host"> Host a Meet and Greet
</label>
<br>
<input type="submit" value="Get More Information">
<br>
</form>
</div>
And in my web routes file I have my two routes setup
Route::get('/contact', function () {
return view('contact');
});
Route::post('/contact', function (Request $request) {
Mail::send(new ContactMail($request));
return redirect('/');
});
I created my Mail file
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $email;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
$this->email = $request;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->subject('New Contact Mail')
->from($this->email->email, $this->email->firstname)
->to('test#gmail.com')
->view('email.contactmail');
}
}
And then my simple blade file
{{ $email->content }}
Whenever I submit the form or try and call the route I get a 500 error and I'm not sure why.

I think you forgot to insert Request $request as a parameter on the class constructor and import the Request class.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Http\Request;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $email;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(Request $request)
{
$this->email = $request;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->subject('New Contact Mail')
->from($this->email->email, $this->email->firstname)
->to('test#gmail.com')
->view('email.contactmail');
}
}
Also, as per your description, you may not have debug on. Change it at .env file:
APP_DEBUG=TRUE

Related

I have the error "InvalidArgumentException Trailing data "

Hi i tried everything i found on Google but nothing work, i have always the error trailing data when i'm trying to insert date in my db. i Hope someone can help me. Thanks a lot and sorry for my english.
//here's my model location
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
protected $table = 'location';
}
//Heres's My migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Location extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('location', function(Blueprint $table) {
$table->bigIncrements('id');
$table->date('start');
$table->date('end');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('location');
}
}
//And here's my method to store date in my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Location;
use Carbon\Carbon ;
public function storeDate(Request $request){
$location = new Location();
$start = Carbon::createFromFormat('m/d/y', $request->input("start"));
$end = Carbon::createFromFormat('m/d/y', $request->input("end"));
$location->start = $start;
$location->end = $end;
$location->save();
return redirect('/myCar');
}
}
My form
<form class="form-inline" method="POST" action="/storedate">
#csrf
<div class="modal-body">
<label class="sr-only" for="inlineFormInputName2"></label>
<input type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="dd/mm/yyyy" value="20/04/2019" name="start">
<label class="sr-only" for="inlineFormInputGroupUsername2"></label>
<div class="input-group mb-2 mr-sm-2">
<input type="text" class="form-control" id="inlineFormInputGroupUsername2" placeholder="dd/mm/yyyy" value="20/04/2019" name="end">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send message</button>
</div>
</form>
It's ok i found it. In m/d/y my y need to be in uppercase :
m/d/Y
Thank you for your support !

Why my post method doesn't work in Laravel?

I've created a form in Laravel to submit registration data to database. I've done this identically as other form in other view that works. Checked for typo's but still when I press submit button, nothing happens.
HTML of form in 'registrations/create.blade.php'
<form method="POST" action="{{route('registrations.store')}}"></form>
<div class="container">
<p>Prašome užpildyti visus laukus.</p>
<hr>
#csrf
<label for="vardas"><b>Vardas</b></label>
<input type="text" placeholder="Įveskite savo vardą" name="vardas" required>
<label for="pavarde"><b>Pavardė</b></label>
<input type="text" placeholder="Įveskite savo pavardę" name="pavarde" required>
<label for="el_pastas"><b>El. paštas</b></label>
<input type="text" placeholder="Įveskite savo el. paštą" name="el_pastas" required>
<label for="tel_nr"><b>Telefono nr.</b></label>
<input type="text" placeholder="Įveskite savo telefono nr." name="tel_nr" required>
<b>Pasirinkite norimą gitaros mokytoją</b><br><br>
<input type="radio" name="mokytojas_id" value="1"> Petras Petrauskas<br>
<input type="radio" name="mokytojas_id" value="2"> Andrius Rimiškis<br>
<input type="radio" name="mokytojas_id" value="3"> Virgis Stakėnas<br>
<hr>
<button type="submit" class="registerbtn"><b>Registruotis</b></button>
</div>
</form>
'routes.web.php'
Route::get('/', 'PagesController#index');
Route::get('/contacts', 'PagesController#contacts');
Route::get('/form', 'PagesController#form');
Route::get('/guitarists', 'PagesController#guitarists');
Route::get('/news', 'PagesController#news');
Route::resource('questions', 'QuestionsController');
Route::resource('registrations', 'RegistrationsController');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin', 'AdminController#dashboard');
Route::resource('guitarists', 'MokytojaiController');
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Registration extends Model
{
protected $fillable = ['vardas', 'pavarde', 'el_pastas', 'tel_nr', 'mokytojas_id'];
}
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Registration;
class RegistrationsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//$questions = DB::select('SELECT * FROM questions');
//$questions = Question::orderBy('id','desc')->take(1)->get();
//$questions = Question::orderBy('id','desc')->get();
$registrations = Registration::orderBy('id','desc')->paginate(10);
return view ('registrations.index')->with('registrations', $registrations);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('registrations.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'vardas' => 'required',
'pavarde' => 'required',
'el_pastas' => 'required',
'tel_nr' => 'required',
'mokytojas_id' => 'required'
]);
$post = $request->all();
Registration::create($post);
return redirect('/registrations/create')->with('status', 'Registracija atlikta!');
}
Your form tag is closed immediately.
<form method="POST" action="{{route('registrations.store')}}"></form>
Is this a type when you posted here or most probably this is the issue. Button is doing nothing since its not inside the form tag.

how to mail value of form not the screenshot of contact.blade.php

I am trying to send mail from my contact form. But I am getting error.
contact.blade.php is:
<form method="post" action="{{ URL('send') }}">
{{csrf_field()}}
<table align="center" width="400">
<tr>
<td><strong>Full Name</strong></td>
<td><input type="text" name="name" required="required" /></td>
</tr>
<tr>
<td><strong>Contact No.</strong></td>
<td><input type="text" name="mobno" required="required" /></td>
</tr>
<tr>
<td><strong>Email ID</strong></td>
<td><input type="text" name="email" required="required" /></td>
</tr>
<tr>
<td><strong>Message</strong></td>
<td><textarea name="msg" cols="30" rows="3" required="required"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" /></td>
</tr>
</table>
</form>
web.php is:
Route::POST('send', 'ContactController#send');
ContactController.php is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\officeholder;
use App\Mail\SendMail;
use Mail;
class ContactController extends Controller
{
public function send()
{
Mail::send(new SendMail());
}
}
**I have created SendMail.php using
php artisan make:mail SendMail
by my cmd and then App\Mail\SendMail.php is created.**
SendMail.php is:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Http\request;
class SendMail extends Mailable
{
use Queueable, SerializesModels;
public function __construct()
{
//
}
public function build(Request $request)
{
return $this->view('contact',['msg'=>$request->msg])->to('mymail#gmail.com');
}
}
But screenshot of my contact.blade.php is sending to my mail, not the value of form and it also not redirect on contact page.
Pass the data in the contructor
class ContactController extends Controller
{
public function send()
{
Mail::send(new SendMail(request()));
redirect()->to('url');
}
}
And in your Mail
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Http\request;
class SendMail extends Mailable
{
use Queueable, SerializesModels;
private $request;
public function __construct( Request $request )
{
$this->request = $request;
}
public function build()
{
return $this->view('contact',['msg'=>$this->request->msg])->to('mymail#gmail.com');
}
}
Hope this helps

Laravel 5: Error in Sending Email

I am trying to send test emails in my Laravel project, and am encountering the following error:
ErrorException in helpers.php line 532:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\...\resources\views\mail-test.blade.php)
I've been toying around with my code, following some guidelines/tutorials online the best I can, but I don't see what I'm doing wrong. Code snippets are as follows:
web.php
Route::post('/send-mail', 'MailController#send')->name('send-mail');
sample-page.blade.php
...
<div style="text-align: center;">
<form action="{{ route('send-mail') }}" method="post">
{{ csrf_field() }}
<input type="email" name="email" placeholder="Email Address">
<input type="text" name="message" placeholder="Insert Message Here.">
<button type="submit">Let's send an email!</button>
</form>
</div>
....
MailController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailer;
use App\Mail\SendMail;
class MailController extends Controller
{
public function send(Request $request, Mailer $mailer) {
$mailer
->to($request->input('email'))
->send(new SendMail($request->input('message')));
return back();
}
}
SendMail.php
...
use Queueable, SerializesModels;
public $message;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('test#test.com')
->view('mail-test');
}
mail-test.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Email Test</title>
</head>
<body>
<h1>EMAIL TESTING</h1>
<p>{{ $message }}</p>
</body>
</html>
The $message variable is automatically passed into the view by Laravel, and it's an instance of the Illuminate/Mail/Message class. If you have a string of content you need to pass to the view, you should do that in the view() call. But you should rename it from $message to avoid conflict. I believe this may do it for you:
SendMail.php
return $this->from('test#test.com')
->view('mail-test', ['contentMessage' => $this->message]);
mail-test.blade.php
<body>
<h1>EMAIL TESTING</h1>
<p>{{ $contentMessage }}</p>
</body>

Laravel Auth::attempt failing each time

I have created a test user on my laravel app. The details are
user: joe#gmail.com pass: 123456
When I go through the registration process everything works as expected and an entry is made into the users table of the database
Once this is finished I redirect the user to the dashboard.
public function postCreate(){
//Rules
$rules = array(
'fname'=>'required|alpha|min:2',
'lname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'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()){
//Save in DB - Success
$user = new User;
$user->fname = Input::get('fname'); //Get the details of form
$user->lname = Input::get('lname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));//Encrypt the password
$user->save();
return Redirect::to('/books')->with('Thank you for Registering!');
}else{
//Display error - Failed
return Redirect::to('/')->with('message', 'The Following Errors occurred')->withErrors($validator)->withInput();
}
}
I then navigate back to the landing page and attempt to log in using the credentials above and I keep getting told that Auth::attempt() is failing hence my user cannot log into the application.
public function login(){
if(Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))){
//Login Success
echo "Success"; die();
return Redirect::to('/books');
}else{
//Login failed
echo "Fail"; die();
return Redirect::to('/')->with('message', 'Your username/password combination was incorrect')->withInput();
}
}
Does anyone know why this is happening? This is the Schema for my users table:
Schema::create('users', function($table){
$table->increments('id');
$table->integer('type')->unsigned();
$table->string('fname', 255);
$table->string('lname', 255);
$table->string('email')->unique();
$table->string('password', 60);
$table->string('school', 255);
$table->string('address_1', 255);
$table->string('address_2', 255);
$table->string('address_3', 255);
$table->string('address_4', 255);
$table->string('remember_token', 100);
$table->timestamps();
});
Any help is much appreciated.
'View for Login':
<div class="page-header">
<h1>Home page</h1>
</div>
<!-- Register Form -->
<form action="{{ action('UsersController#postCreate') }}" method="post" role="form">
<h2 class="form-signup-heading">Register</h2>
<!-- Display Errors -->
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<!-- First Name -->
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" name="fname" />
</div>
<!-- Last Name -->
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" name="lname" />
</div>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<!-- Confirm Password -->
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" name="password_confirmation" />
</div>
<input type="submit" value="Register" class="btn btn-primary"/>
</form>
<!-- Login Form -->
<form action="{{ action('UsersController#login') }}" method="post" role="form">
<h2 class="form-signup-heading">Login</h2>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<input type="submit" value="Login" class="btn btn-primary"/>
</form>
Can you run this function below - and tell me where the error occurs? It will diagnose the problem:
public function testLogin()
{
$user = new User;
$user->fname = 'joe';
$user->lname = 'joe';
$user->email = 'joe#gmail.com';
$user->password = Hash::make('123456');
if ( ! ($user->save()))
{
dd('user is not being saved to database properly - this is the problem');
}
if ( ! (Hash::check('123456', Hash::make('123456'))))
{
dd('hashing of password is not working correctly - this is the problem');
}
if ( ! (Auth::attempt(array('email' => 'joe#gmail.com', 'password' => '123456'))))
{
dd('storage of user password is not working correctly - this is the problem');
}
else
{
dd('everything is working when the correct data is supplied - so the problem is related to your forms and the data being passed to the function');
}
}
Edit: one thought - are you sure the user is being correctly saved in the database? Have you tried to 'empty/delete' your database and try your code again? In your current code, it will fail if you keep registering with joe#gmail.com - because it is unique. But you dont catch the error anywhere. So empty the database and try again...
Edit 2: I found another question you posted with the same problem - and in there you mentioned that the following code is your user model?
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function getAuthIdentifier() {
}
public function getAuthPassword() {
}
public function getRememberToken() {
}
public function getRememberTokenName() {
}
public function getReminderEmail() {
}
public function setRememberToken($value) {
}
}
Is that EXACTLY your current user model? Because if so - it is wrong - none of those functions should be blank.
This is what a CORRECT user model should look like for Laravel 4.2
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
You would make sure about:
your model:
mine looks like:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
public function getAuthIdentifier()
{
Return $this->getKey ();
}
public function getAuthPassword()
{
return $this->password;
}
}
make sure your app/config/auth.php is configured correctly
make sure app/config/app.php has service provider
'Illuminate\Auth\AuthServiceProvider',
Make sure your controller class has auth. before writing class you have used Auth (I mean include Auth class)
That all could make Auth doesn't work well
With password hashing enabled, the User model must override these methods:
public function getAuthIdentifierName()
{
return 'email';
}
public function getAuthIdentifier()
{
return request()->get('email');
}
public function getAuthPassword()
{
return Hash::make(request()->get('password'));
}
What is the value for strlen(Hash::make(Input::get('password')))? If it is greater than 60, then this would cause the authentication to fail each time, as the stored password is not the full hash.
Good day, here is what I discovered when I encountered the same error: A simple string compare will reveal that the two hashing methods produce two different hashed values.
echo strcmp(Hash::make('password'),bcrypt('password'));
My assumption is that Auth::attempt([]) uses bcrypt() to hash out passwords which produces a different value to what you used Hash:make().

Categories