How to fetch the name of the url inside the laravel mailer? - php

I have a webpage with 4 different urls
www.sample.com\home
www.sample.com\about
www.sample.com\products
www.sample.com\contact
I have a contact form in all the pages of my webpage.
I need to know the Page, from where the contact form is submitted from either(home, about, products or services).
I use laravel mailer to send mail, once the contact form is submitted.
Contact form:
<input type="hidden" name="url" value="{{substr(strrchr(url()->current(),'/'),1)}}">
<form method="POST" action="sendEmail">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="{{ old('name') }}" />
<label for="email">Email</label>
<input type="email" name="email" id="email" value ="{{ old('email') }}"/>
<label for="message">Message</label>
<textarea name="body" id="message" rows="5"> {{ old('message') }}</textarea>
<button class ="primary"> Submit </button>
</form>
Controller:
use Illuminate\Support\Facades\Request as PostRequest;
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required'
]);
// To get the current URL
$currentPage = PostRequest::input('url');
\Mail::send('E-mail view', $data, $currentPage, function($message) use ($data, $currentPage){
$message->to('abc#xyz.com')
->from($data['email'], $data['name'])
->replyTo($data['email'], $data['name'])
->returnPath($currentPage)
->subject('Notification');
});
return back();
}
I need the URL as home, about, products, contact, from where the Contact form is submitted from not the form action sendEmail inside the E-mail View blade file
Email View Blade:
<p> $name </p>
<p> $email</p>
<p> $currentPage </p>
It throws an Error
Function name must be a string
How to pass the current URL from Where the Form is submiited from (home, about,..) to Mail?
Could anyone please help?
Many thanks.

Try like this
use Illuminate\Support\Facades\Request as PostRequest;
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required'
]);
// To get the current URL
$currentPage = request()->url();
$data['currentPage'] = $currentPage;
\Mail::send('E-mail view', $data, function($message) use ($data, $currentPage){
$message->to('abc#xyz.com')
->from($data['email'], $data['name'])
->replyTo($data['email'], $data['name'])
->returnPath($currentPage)
->subject('Notification');
});
return back();
}

Related

Validator Does Not Show Errors At Blade

I have a Controller method like this:
use Validator;
public function insert(Request $request)
{
$data = Validator::make(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
])->validated();
$wallet = new Wallet();
$wallet->title = $data['title'];
$wallet->name = $data['name'];
if (!empty($data['activation'])) {
$wallet->is_active = 1;
} else {
$wallet->is_active = 0;
}
if (!empty($data['cachable'])) {
$wallet->is_cachable = 1;
} else {
$wallet->is_cachable = 0;
}
$wallet->save();
return redirect(url('admin/wallets/index'));
}
And then I tried showing errors like this:
#error("name")
<div class="alert alert-danger">{{$message}}</div>
#enderror
But the problem is, it does not print any error when I fill the form incorrectly.
So how to fix this and show errors properly?
Here is the form itself, however it submits data to the DB correctly:
<form action="{{ route('insertWallet') }}" method="POST" enctype="multipart/form-data">
#csrf
<label for="title" class="control-label">Title</label>
<br>
<input type="text" id="title-shop" name="title" class="form-control" value="" autofocus>
#error("title")
<div class="alert alert-danger">{{$message}}</div>
#enderror
<label for="title" class="control-label">Name</label>
<br>
<input type="text" id="title-shop" name="name" class="form-control" value="" autofocus>
#error("name")
<div class="alert alert-danger">{{$message}}</div>
#enderror
<input class="form-check-input" type="checkbox" name="cachable" value="cashable" id="cacheStatus">
<label class="form-check-label" for="cacheStatus">
With Cash
</label>
<input class="form-check-input" type="checkbox" name="activaton" value="active" id="activationStatus">
<label class="form-check-label" for="activationStatus">
Be Active
</label>
<button class="btn btn-success">Submit</button>
</form>
check the official documentation here
add the following code
if($data->fails()){
return redirect(url('admin/wallets/index'))->withErrors($data)->withInput();
}
And after that save your data in your database
You are not returning any errors, you are just redirecting back to the view without any data.
Your fix would be to have your validator as this:
$data = Validator::validate(request()->all(),[
'title' => 'required',
'name' => 'required|alpha_num',
'activation' => 'nullable',
'cachable' => 'nullable'
]);
See that I have changed Validator::make to Validator::validate. As the documentation states:
If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.
If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.
So, if your validation passes, it will save all the validated data into $data, as you did with ->validated() (but you don't have to write it here), and if it fails, it will automatically throw an Exception, in this case ValidationException, so Laravel will automatically handle it and redirect back with to the same URL and with the errors. So it now should work...
This is the Validator::validate source code and this is the validate source code for the validator validate method.

Difficulty in changing old email to new email in Laravel

I'm having a difficulty to change the current user's email to a new email which is user input and the email's validation. EDITED
Here's my controller
public function changeuser(Request $request){
$id = Auth::user()->id;
$change_user = User::find($id);
$valid = validator($request->only('oldpass', 'newpass', 'confirmpass'), [
'olduser' => 'required|email|max:255|exists:users',
'newuser' => 'required|email|max:255|different:olduser'
], [
'newuser.required_with' => 'Choose different email.'
]);
if ($valid->fails()) {
return redirect('/manageaccount')->with('message','Failed to update email');
}
$change_user->email = $request->input('newuser');
$change_user->save();
return redirect('/manageaccount')->with('message', 'email changed successfully');
}
my blade.php which is in modal
<div class="thirdea" id="thirdea">
<label><p class="small Montserrat">Enter Old Username</p></label>
<input type="text" class="form-control small Montserrat" name="olduser" value="" id="olduser">
<label><p class="small Montserrat"> New Username</p></label>
<input type="text" class="form-control small Montserrat" name="newuser" value="" id="newuser">
</div>
my route
Route::post('/changeuser/','UserController#changeuser');
In case of update user you can try validations for email like this :
$validate = $request -> validate([
'newuser' => 'required|unique:users,email,'.$user->id
]);

isMethod does not work

Here is my content.blade.php
<form action="{{ route('home') }}" method="post">
<input class="input-text" type="text" name="name" value="Your Name *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<input class="input-text" type="text" name="email" value="Your E-mail *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<textarea name="text" class="input-text text-area" cols="0" rows="0" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">Your Message *</textarea>
<input class="input-btn" type="submit" value="send message">
{{ csrf_field() }}
</form>
That's my routes(web.php)
Route::group(['middleware'=>'web'], function(){
Route::match(['get', 'post'], '/', ['uses'=>'IndexController#execute', 'as'=>'home']);
Route::get('/page/{alias}', ['uses'=>'PageController#execute', 'as'=>'page']);
Route::auth();
});
And Finally here is my IndexController.php, method execute():
if($request->isMethod('post')){
$messages = [
'required' => "Поле :attribute обязательно к заполнению",
'email' => "Поле :attribute должно соответствовать email адресу"
];
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'text' => 'required'
], $messages);
dump($request);
}
So, the problem is that dump($request) does not work, and I also tried to comment everything except dump($request), and the result is the same. I think it just skips if($request->isMethod('post')) so that it returns that the method is not true, may be there is something wrong with token, I am not sure.
How to resolve this issue?
edit:
That's the code above if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Page;
use App\Service;
use App\Portfolio;
use App\People;
use DB;
class IndexController extends Controller
{
//
public function execute(Request $request){
You should assign $request to somewhere first.
For example, if i have a store method and i have to use Request $request for grabbing the information, i should establish it first, so by establishing it my application will recognize what does the variable is retrieving, let me show you an example code:
public function store(Request $request)
{
$data = $request->all();
$data['a'] = Input::get('a');
$data['b'] = Input::get('b');
$data['c'] = Input::get('c');
$data['d'] = Input::get('d');
$data['e'] = Input::get('e');
Letters::create($data);
return redirect::to('/');
}
Did you get it?
If not, here is an example with isMethod:
$method = $request->method();
if ($request->isMethod('post')) {
//
}
In your code i did not see the $var = $request->method(); (or what you want it to be).

PHP: Empty function not working properly

I'm new to laravel and have been going through this code for hours, yet I'm unable to figure out what's really wrong.
I have this form:
<form method="POST" action="{{ action('School1Controller#forgot_password') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" class="form-control" name="matricule" placeholder="Matricule No. or name" >
<input type="email" class="form-control" name="inst_email" placeholder="Password">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
which submits to this method..
public function forgot_password(Request $request){
$this->validate($request, [
'matricule' => 'required',
'inst_email' => 'required'
]);
$input = $request->all();
$student = User::where('matricule', $input['matricule'])->where('inst_email', $input['inst_email'])->get();
// dd($student);
if (empty($student)){
Session::flash('message', 'We have no such user in our records.');
return redirect()->back();
}else{
Session::flash('message', 'Student found. We will reset your password soon.');
return redirect()->back();
}
}
..through this route..
Route::post('/forgot_password', ['as' => 'forgot_password', 'uses' => 'School1Controller#forgot_password']);
When it queries the database, it returns the student properly and I can display it using dd($student). In cases when the student is unavailable, it also displays an empty array. Now the problem is, the message that keeps displaying is that which says student is found regardless whether the $student array holds any student or not. Is there a problem with my empty() function or what?

Laravel 5.1 registration form with new field

I am creating referral system so I have the following routes
// Registration routes...
Route::get('auth/register/{id}', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
and my RegisterUser.php is changed to
public function getRegister($id)
{
return view('auth.register')->withName($id);
}
and my blade looks like
<div class="form-group">
<label class="col-md-4 control-label">Company</label>
<div class="col-md-6">
<input type="text" class="form-control" name="company" value="{{ old('company') }}" readonly disabled>
</div>
</div>
in AuthController I have:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'company' => $data['company'],
'password' => bcrypt($data['password']),
]);
}
and the value="{{ old('company') }}" is causing the problem. When it is like that it works. But I want the value to be value="{{$name}}" given from return view('auth.register')->withName($id); So when I go to route auth/register/something in the input field I have got the 'something' so it is working but I have the error code "Undefined index: company". When I remove the value at all it is working but I need this value. Any suggestions would be helpful.
The Problem of your code is the disabled attribute in the input "company", why ? well a disabled element isn't editable and isn't sent on submit. so Laravel doesn't receive it so you will be able to access via the helpers old.
Remove the disabled attribute and the magic happens.
<input type="text" class="form-control" name="company" value="{{ old('company') }}" readonly >

Categories