I am trying to submit a form and send an email based on data submitted through the form, but it doesn't seem to be working because I don't get back the success message.
Controller
public function contact(Request $request)
{
$request = request()->validate([
'name' => 'required',
'email' => 'required| email',
'message' => 'required | max:1000',
]);
Mail::to('support#mail.com')->send(new contact($request));
return redirect()->back()->with("success", "You email has successfully been sent");
}
Form
#if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
#endif
#if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
#endif
<form action="/contact" method="POST">
#csrf
<div class="col-md-12">
<input type="text" placeholder="Full Name" required name="name">
</div>
<div class="col-md-8">
<input type="text" placeholder="email" required name="email">
</div>
<div class="col-md-2">
<textarea name="message"></textarea>
</div>
<div class="col-md-12">
<button class="btn btn-black no-margin-bottom btn-small"
type="submit">Contact</button>
</div>
</form>
Route
`Route::post('/contact', 'HomeController#contact');`
If you're being redirected back to the form page without error messages or your sucess flash message then I am inclined to think the problem is in your template. Assuming you are using the laracasts/flash package your method should look like this
public function contact(Request $request)
{
$request = request()->validate([
'name' => 'required',
'email' => 'required| email',
'message' => 'required | max:1000'
]);
Mail::to('support#mail.com')->send(
new contact($request)
);
return redirect()->back()->with("success", "You email has successfully been sent");
}
redirect()->with() adds data to the session but it doesn't display a message unless you manually do so in the template like this
#if (session('sucess'))
<div class="alert alert-success">
{{ session('success') }}
</div>
#endif
Make sure you're displaying errors properly in your form, replace your session('error') block with the following:
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In your controller:
use App\Mail\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class HomeController extends Controller
{
// ...
public function contact(Request $request)
{
// Note I'm not overwriting the $request variable.
// This method returns an array of the validated data.
$request->validate([
'name' => 'required',
'email' => 'required|email',
'message' => 'required|max:1000'
]);
Mail::to('support#mail.com')->send(new Contact($request));
return back()->with('success', 'Your email has successfully been sent');
}
}
Your mail class should look something like this:
namespace App\Mail;
use Illuminate\Http\Request;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Contact extends Mailable
{
use Queueable, SerializesModels;
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function build()
{
// The request instance must be passed to the view...
return $this->markdown('emails.contact', [
'request' => $this->request
]);
}
}
You can now use the Request object in your email markdown (emails.contact). For example:
**Name**<br>
{{ $request->input('name') }}
**Email**<br>
{{ $request->input('email') }}
**Message**<br>
{{ $request->input('message') }}
Related
I've a trait function that updating a report, i've done its route and its namespace also im using it in the controller everything is right but when i submit it doesn't run and the page only refreshs
Trait Function
<?php
namespace App\Http\Controllers\Permit\Trait;
use App\Models\Log;
use App\Models\Permit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
trait HazardsInfo
{
public function HazardsInfo(Request $request, $id)
{
dd($request);
$permit = Permit::findOrFail($id);
$permit->Update([
'gaurd_names' => $request->gaurd_names,
]);
Log::create([
'permit_id' => $permit->id,
'created_by' => Auth::user()->id,
'status' => 'og-complete'
]);
return Redirect::to("/permit/{$id}/edit")->withSuccess('Hazards Has Been Updated');
}
}
Route
Route::post('/permit/{permit}/edit', [PermitController::class, 'HazardsInfo'])->name('permit.HazardsInfo');
blade form
<form action="{{ route('permit.HazardsInfo', $permit->id) }}">
#if (Session::has('success'))
<div class="alert alert-success w-25 ms-2 text-center">
{{ Session::get('success') }}
</div>
#endif
<input type="text" name="gaurd_names">
<button type="submit" class="btn btn-success btn-label right ms-auto nexttab nexttab" data-nexttab=""><i
class="ri-arrow-left-line label-icon align-middle fs-16 ms-2"></i>
Submit</button>
</form>
form
When i submit the form it redirects back to the form itself, can anyone help me?
<form action="/jisajili" method="POST">
#csrf
<div class="card-panel z-depth-5">
<h5 class="center red-text">Jiunge Nasi</h5>
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="username" class="validate">
<label>Jina lako</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input type="number" name="phone" class="validate">
<label>Nambari ya simu</label>
</div>
....
</p>
<input type="submit" name="submit" value="Jiunge" class="btn left col s12 red">
Controller
class registration extends Controller{
public function create(){
return view('jisajili.jiunge');
}
public function store(Request $request){
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$cpassword = $request -> input('cpassword');
$reg->save();
$validated = $request->validate([
'name' => 'required|unique:posts|max:10',
'body' => 'required',
]);
return redirect('home');
}
}
What I would do is first check for the data requirements before you add the object to the database. Also I would add the columns of the models into the Model file to use the Object::create function with an array parameter.
I recomment to use routing in your blade file. I noticed you used action="/route". What you want to do is naming your routes with ->name('route_name') in the route files. To use them in your blade files with the global route function route="{{ route('route_name') }}".
<?php
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function store(\Illuminate\Http\Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|unique:posts|max:10',
'body' => 'required'
]
);
// Go back with errors when errors found
if ($validator->fails()) {
redirect()->back()->with($validator);
}
Post::create(
[
'name' => $request->get('name'),
'body' => $request->get('body')
]
);
return redirect()
->to(route('home'))
->with('message', 'The post has been added successfully!');
}
}
What you can do after this is adding custom errors into the controller or add them into your blade file. You can find more about this in the documentation of Laravel.
it redirects you back because of validation error.
change password confirmation name from cpassword into password_confirmation as mentioned in laravel docs
https://laravel.com/docs/7.x/validation#rule-confirmed
update your controller into:
public function store(Request $request){
$validated = $request->validate([
'username' => 'required',
'phone' => 'required',
'email' => 'required',
'password' => 'required|confirmed'
]);
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$reg->save();
return redirect('home');
}
in your blade add the following to display validation errors:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I'm start learning laravel and want to create sample login authorization system on my html template. I watched a tutorial and when i do everything that was in video i get error Undefined variable: erros.
I'm new and I don't know good PHP but i want to learn while creating a website I know a little.
my rout code is my route code :
this is route for my login code
Route::get ('/main', 'MainController#index');
Route::get ('/main/checklogin', 'MainController#checklogin');
Route::get ('/main/successlogin', 'MainController#successlogin');
Route::get ('/main/logout', 'MainController#logout');
1.my login code
<div class="login slide-up">
<div class="center">
<h2 class="form-title" id="login"><span>sign</span>in</h2>
#if (isset(Auth::user()->email))
<script>window.location="/main/successlogin"</script>
#endif
#if ($message = Session::get('error'))
<div class ="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">X</button>
<strong>{{$message}}</strong>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
#if(count($errors) >0 )
<div class="alert alert-danger">
<ul>
#foreach($erros->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
{{ csrf_field()}}
<div class="form-holder">
<input type="email" class="input" placeholder="email" />
<input type="password" class="input" placeholder="password" />
</div>
<button class="submit-btn">Sign in</button>
</div>
2.my successlogin code
<html>
<body>
#if (issets(auth::user()->email))
<p>gamarjoba {{Auth::user()->email}}}</p>
<a href="{{ url('/main/logout') }}" > logout </a>
else
<script>windows.location = "/main"; </script>
#endif
</body>
</html>
my main controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
class MainController extends Controller
{
function index()
{
return view('front/login');
}
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:4'
]);
$user_data = array(
'email' => $request -> get('email'),
'password' => $request -> get('password')
);
if (Auth::attempt($user_data))
{
return redirect('main/successlogin');
}
else
{
return back()->with('error', 'wrong Login Details');
}
}
function successlogin()
{
return view('successlogin');
}
function logout()
{
Auth::logout();
return redirect('main');
}
}
Laravel made this easy:
Run php artisan make:auth
I created custom login system on LARAVEL app, everything has worked perfectly until yesterday. When i typed in login form email and password for user that is same as from database, system redirect me back. I don't know what is problem, i cleared cache and everything but still it doesn't work. If someone know answer i would really appreciate.
Login page image:
https://imgur.com/a/xuEWQZg
Data of user stored in database whit seed :
https://imgur.com/0mJOviV
`
dd function with sent data from login form :
` https://imgur.com/a/D2k8Ztn
Main controller
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data = array(
'email' => $request->get('email'),
'password' => $request->get('password')
);
if(Auth::attempt($user_data))
{
return redirect('');
}
else
{
return back()->with('error', 'you typed wrong data');
}
}
login page
#extends('layout')
#section('content')
<div class="container2">
<div class="container">
<div class="card card-container">
<h1 style="text-align: center;">Admin login</h1>
#if(isset(Auth::user()->email))
<script>window.location="/main/successlogin";</script>
#endif
#if ($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ url('/main/checklogin') }}">
{{ csrf_field() }}
<div class="form-group">
<label>Unesi email</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label>Unesi šifru</label>
<input type="password" name="password" class="form-control" />
</div>
<div class="form-group">
<input type="submit" name="login" class="btn btn-primary" value="Login" />
</div>
</form>
</div><!-- /card-container -->
</div><!-- /container -->
</div><!-- /container -->
#endsection
Routes
Route::get('/', 'MainController#successlogin')->name('main');
Route::get('/admin', 'MainController#index');
Route::post('/main/checklogin', 'MainController#checklogin');
Route::get('main/logout', 'MainController#logout');
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'lastname', 'level',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Try this:
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data = array(
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
);
if(Auth::attempt($user_data))
{
return redirect('');
}
else
{
return back()->with('error', 'you typed wrong data');
}
}
I'm making my first form in Laravel and the generation of the form is all working. It's just that the store function seems to blindly return the user to my contact page irrelevant of the result of the form validation.
So if the email address posted isn't an email but a random string I still get returned to the /contact page with the thank you message being sent to the view.
My controller looks like this:
namespace App\Http\Controllers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\ContactFormRequest;
class ContactController extends Controller {
public function create(){
return view('contact');
}
public function store(ContactFormRequest $request) {
return \Redirect::route('contact')
->with('message', 'Thanks for contacting us!');
}
}
And the form handler like this:
namespace App\Http\Requests;
use Illuminate\Http\Request;
class ContactFormRequest extends Request {
public function authorize() {
return true; // don't need to be registered to run form so true
}
public function rules() {
return [
'email' => 'required|email',
];
}
}
This is controlled by the following routes
if (config('app.tan_site_page_contact')===true){
Route::get('/contact', ['as' => 'contact', 'uses' => 'ContactController#create']);
Route::post('/contact', ['as' => 'contact_store', 'uses' => 'ContactController#store']);
});
And the form like this:
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
#endif
{!! Form::open(array('route' => 'contact_store', 'id' => 'contactCallMeForm')) !!}
{!! Form::label('Your E-mail Address') !!}
{!! Form::text('email', null, array('required', 'class'=>'form-control', 'placeholder'=>'Your e-mail address')) !!}
{!! Form::submit('Contact Us!', array('class'=>'btn btn-primary')) !!}
{!! Form::close() !!}
The form html seems fine,with a token and valid url
<form method="POST" action="http://localhost/contact" accept-charset="UTF-8" id="contactCallMeForm" novalidate="">
<input name="_token" type="hidden" value="VNHchLZhfsXadVZXCZWHGdAuJ4zgmO6cDJIGhR59">
<label for="Your E-mail Address">Your E-mail Address</label>
<input required="required" class="form-control" placeholder="Your e-mail address" name="email" type="text">
<input class="btn btn-primary" type="submit" value="Contact Us!">
</form>
The problem here is your ContactFormRequest class.
You extends it from invalid Request class. You extend it from \Illuminate\Http\Request class but you should extend it from \Illuminate\Foundation\Http\FormRequest (or \App\Http\Requests\Request class)