Issues with Laravel Mailables - laravel

I'm trying to create a contact form in Laravel using Laravel 5.3, but I get this nasty error here:
ErrorException in helpers.php line 519:
htmlspecialchars() expects parameter 1 to be string, object given (View: /Applications/XAMPP/xamppfiles/htdocs/meps/resources/views/emails/contactemail.blade.php)
Here are the files that I was using:
The contact form
<div class="contact-form">
<form class="margin-clear" role="form" action="{{ url('/sendmail') }}" method="POST">
{{ csrf_field() }}
<div class="form-group has-feedback">
<label for="name">Name*</label>
<input type="text" class="form-control" id="name" name="name" placeholder="">
<i class="fa fa-user form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label for="email">Email*</label>
<input type="email" class="form-control" id="email" name="email" placeholder="">
<i class="fa fa-envelope form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label for="subject">Subject*</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="">
<i class="fa fa-navicon form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label for="message">Message*</label>
<textarea class="form-control" rows="6" id="message" name="message" placeholder=""></textarea>
<i class="fa fa-pencil form-control-feedback"></i>
</div>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
</div>
The Controller function
public function sendmail(Request $request, Mailer $mail) {
$mail->to('kaley36_aw#yahoo.com')->send(new ContactEmail($request->name, $request->email, $request->subject, $request->message));
$request->session()->flash('mail-sent', 'Your email has been sent.');
return redirect('/contact');
}
The Mailable class
class ContactEmail extends Mailable
{
use Queueable, SerializesModels;
public $name;
public $email;
public $subject;
public $message;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($name, $email, $subject, $message)
{
$this->name = $name;
$this->email = $email;
$this->subject = $subject;
$this->message = $message;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($this->email)->view('emails.contactemail');
}
}
And here is the route
Route::post('sendmail', 'EmailController#sendmail');

You probably looking at the wrong view. The error points to
/views/emails/contactemail.blade.php
But this view has a <form> unless you are sending back to your users a form via e-mail, this looks a lot more like your contact form view and not your e-mail view. Something like:
/views/contact.blade.php (or whatever you have in there as a form)
As for the error, you must have a {{ $variable or functionCall() }} which is not receiving a string, but an object.

I figured it out. The issue was with the variable $message, Laravel wrapped it in an actual object called Message. All I had to do was change the variable name to $theMessage and it worked find.

Related

Laravel 8 Form Request Validation Redirect to Index page instead same page and show error

On localhost all is good, but when I deploy the application to the server not working. If form request validation fails instead of bringing me back to the same page and showing an error, it redirects me to the index page.
config.blade.php
<form method="POST" action="{{ route('config.update', $config->id) }}">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col">
<label class="col-form-label">Name</label>
<input id="name" type="text" class="form-control" name="name" value="{{ $config->name }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Address</label>
<input id="address" type="text" class="form-control" name="address" value="{{ $config->address }}">
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Phone</label>
<input id="phone" type="tel" class="form-control" name="phone" value="{{ $config->phone }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">E-mail</label>
<input id="email" type="email" class="form-control" name="email" value="{{ $config->email }}" required>
</div>
</div>
<div class="form-group row mt-4 mb-0">
<div class="col-md-12">
<button type="submit" class="btn btn-primary button-full-width">Save changes</button>
</div>
</div>
</form>
web.php
Route::resource('/admin/config', 'Admin\ConfigController');
ConfigController
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Services\ConfigServices;
use App\Http\Requests\ConfigRequest;
use App\Models\Config;
class ConfigController extends Controller
{
protected $configServices;
public function __construct(ConfigServices $configServices) {
$this->middleware('auth');
$this->configServices = $configServices;
}
...
public function update(ConfigRequest $request, $id)
{
$config = $this->configServices->updateConfigById($request, $id);
return redirect()->back();
}
...
}
ConfigRequest - here is the problem
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ConfigRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'address' => 'nullable|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:9|max:15',
'email' => 'required|email:rfc',
];
}
}
Form Request return to index page instead same page. On localhost working everything, but when I deploy the app to server a problem arises.
When data on form request validated correct return me back on the same page and show success, but when form request failing redirect mine for some reason to the index page.
A problem arises in Laravel 8, this code worked well in previous Laravel versions.
Can someone help me, please?
In your custom request you need:
/**
* The URI that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirect = '/dashboard';
or
/**
* The route that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirectRoute = 'dashboard';
You can find more in the docs.
In the docs for older versions of Laravel these properties don't exist.
Do you have error parts in your blade?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#if ($message = Session::get('unique'))
asdsad
#endif
#endforeach
</ul>
</div>
#endif

How do I send email to multiple users from a single email form? laravel 8

In my application, I can send an email to a single user!
but I want to send to multiple users at the same time from a single form!
My class
class SendEvent extends Mailable {
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data) {
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build() {
return $this->markdown('emails.eventEmail');
}
}
This is the send() function below.
My controller
class EmailController extends Controller {
public function send(Request $request) {
$homeUrl = url('/');
$eventId = $request->get('event_id');
$eventTitle = $request->get('event_title');
$eventUrl = $homeUrl.'/'.'events/'.$eventId.'/'.$eventTitle;
$data = array(
'your_name'=>$request->get('your_name'),
'your_email'=>$request->get('your_email'),
'friend_name'=>$request->get('friend_name'),
'eventUrl'=>$eventUrl
);
$emailTo = $request->get('friend_email');
Mail::to($emailTo)->send(new SendEvent($data));
return redirect()->back()->with('message','Event link sent to '.$emailTo);
}
}
Here in the recipient address form, I can only add just one address!
My form in the model
<form action="{{route('mail')}}" method="POST">#csrf
<div class="modal-body">
<input type="hidden" name="event_id" value="{{$event->id}}">
<input type="hidden" name="event_title" value="{{$event->title}}">
<div class="form-goup">
<label>Your name * </label>
<input type="text" name="your_name" class="form-control" required="">
</div>
<div class="form-goup">
<label>Your email *</label>
<input type="email" name="your_email" class="form-control" required="">
</div>
<div class="form-goup">
<label>Person name *</label>
<input type="text" name="friend_name" class="form-control" required="">
</div>
<div class="form-goup">
<label>Person email *</label>
<input type="email" name="friend_email" class="form-control" required="">
</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">Mail this event</button>
</div>
</form>
How do I get my code to send to more than one email address from my form?
I think you can solve it by making $friend_name an array
<input type="email" name="friend_email[]" class="form-control" required="">
and then you may add a js function to append this input for more emails
something like that
$( "#form" ).append( "<input type="email" name="friend_email[]" class="form-control"
required="">
" );
and that's it.
The friend_email will be passed to the Mail as an array and every email in it will receive the mail

Laravel 5.8 authentication

Hi i've a problem with laravel authentication system (5.8) The problem is that I need to login two times to enter my site
My routes file is
Route::get('/', 'RefundsController#index');
Route::get('/polizza', 'RefundsController#indexRefunds')->name('polizza');
Auth::routes();
--------------other routes------------------
RefundsController
public function __construct()
{
$this->middleware('auth');
}
public function index(){
return view('auth.login');
}
public function indexRefunds(Request $request){
DB::enableQueryLog();
$grafici = 1;
$getAverageLiquidati = DB::table('refunds')
->select(DB::raw("AVG(DATEDIFF(date_liq, date_ref)) AS avgliq"))
->where([
['disactive','=', 1],
['date_liq','<>','0000-00-00'],
['status_ref','>', 5]
])
->get();
$getAverageRifiutati = DB::table('refunds')
->select(DB::raw("AVG(DATEDIFF(date_status, date_ref)) AS avgrif"))
->where(function($q) {
$q->where('status_ref','=', 2)
->orWhere('status_ref','=', 3)
->orWhere('status_ref','=', 4);
})
->where([
['disactive','=', 1],
['date_liq','<>','0000-00-00'],
])
->get();
//dd(DB::getQueryLog());
//dd($getAverageRifiutati);
return view('pages.modify', compact('grafici','getAverageLiquidati','getAverageRifiutati'));
}
login blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<!--<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{-- old('remember') ? 'checked' : '' --}}>
<label class="form-check-label" for="remember">
{{-- __('Remember Me') --}}
</label>
</div>
</div>
</div>-->
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
{{--#if (Route::has('password.request'))--}}
<!--<a class="btn btn-link" href="{{-- route('password.request') --}}">
{{-- __('Forgot Your Password?') --}}
</a>-->
{{--#endif--}}
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
my LoginController
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/polizza';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
In my Middleware
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/polizza');
}
return $next($request);
}
}
When i connect to https://www.example.com/refunds/ because of definition in RefundsController it takes me to https://www.example.com/refunds/login but when i insert credentials it takes me to https://www.example.com/refunds/ with again login form then when i insert credentials it finally takes me to https://www.example.com/refunds/polizza
I dont understand why :(
The first redirect happens because in your Controller constructor, you are setting the middleware to auth. Hence, all unauthorized requests to any methods in that Controller will be redirected to default log in page. (https://www.example.com/refunds/ redirects to https://www.example.com/refunds/login)
When you enter your credentials there, Laravel takes you to your intended route (the route you tried to access without being authenticated, and that is https://www.example.com/refunds/).
This time you are authenticated, so in your controller, your index method is set to return log in view, so the view is being returned and rendered, and the form is being shown for the second time now. Now, that you log in for the second time, the Log In controller will redirect you to https://www.example.com/refunds/polizza, as there intended route does not exists, and it uses the default route which is correctly set to /polizza.
How to resolve this issue?
In your controller's constructor, change the line with:
$this->middleware('auth')->except(['index']);
This way, you will exclude the index function from the auth middleware and it can be accessible to the public. The request should no longer redirect you to the default log in page. Now, going to https://www.example.com/refunds/ will just render a log in form, as you specified in your controller. When you log in with that form, it will take you to /polizza route.

Laravel login not working properly after changing the default username and password

I have a custom table for users named 'iw_users' and inside, i have also a custom column for email and password named 'iu_email' and 'iu_password'. What i want to do here is to set my iu_email as the email and iu_password as a password on login, register, and forgot password (basically all functionalities that laravel Auth provides).
I have followed the answer on this thread: Laravel: How can i change the default Auth Password field name
But when i try to login (with correct credentials) the page is just refreshing and redirecting me again to log in page (I can confirm that laravel did not authorize me using Auth::check()).
Also, the color of the error and input are not red whenever i try to login with wrong credentials.
This is my App\User code:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'iw_users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'iu_user_id', 'iu_last_name', 'iu_first_name', 'iu_email', 'iu_mobile_no', 'iu_password', 'iu_gender', 'iu_country', 'iu_role', 'iu_photo', 'iu_status', 'iu_ipaddress'
];
public function getAuthPassword()
{
return $this->iu_password;
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
// Commented. i don't have 'password' and 'remember_token' in iw_users
// protected $hidden = [
// 'password', 'remember_token',
// ];
}
This is my LoginController.php
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'iu_email';
}
}
This is my login.blade.php form
<form class="form-horizontal" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="iu_email" value="{{ old('iu_email') }}" required autofocus>
#if ($errors->has('iu_email'))
<span class="help-block">
<strong>{{ $errors->first('iu_email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
I would suggest you to check https://scotch.io/#sukelali/how-to-create-multi-table-authentication-in-laravel
Have you got any error while debugging this? I doubt, it's unable to override their default fields.

How to store data in foreign key of a user table

The question is pretty simple. I am storing user's form data into table. I am using Auth login system of laravel, when user fill the input fields and register all values received in array called $data in create function (as you know code written in laravel as default) but when I save it in table, all values save expect department_id that is a foreign key. There is also a candidate_id and it is also a foreign key of candidate_table and it also save, but department_id have some issue.
Blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="{{ route('register') }}">
{{ csrf_field() }}
{{--<input style="text-transform: capitalize;" id="test" type="number" class="form-control" name="id" required autofocus>--}}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input style="text-transform: capitalize;" id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<input style="text-transform: capitalize;" id="department" type="number" class="form-control" name="department" required autofocus>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function candidate()
{
return $this->belongsTo(Candidate::class,'candidate_id');
}
public function department()
{
return $this->belongsTo(Department::class,'department_id');
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name','email','password','image','candidate_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Department;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
// 'candidate_id' => $data['id'],
'password' => bcrypt($data['password']),
'department_id' => $data['department'],
]);
}
}
As you can see, for department_id input you have commented out form input field.
{{--<input style="text-transform: capitalize;" id="test" type="number" class="form-control" name="id" required autofocus>--}}
Uncomment the code and it will work fine.
And because of it, it will not store department_id
Try changing...
protected $fillable = [
'name','email','password','image','candidate_id'
];
to
protected $fillable = [
'name','email','password','image','candidate_id','department_id'
];

Resources