Laravel mail - no message body [duplicate] - php

This question already has an answer here:
Laravel htmlspecialchars() error when sending email
(1 answer)
Closed 1 year ago.
ErrorException
htmlspecialchars() expects parameter 1 to be string, object given (View: F:\OWL\owl-technical\resources\views\emails\contact-mail.blade.php)
This error appears after I try to send a message from the form on the contact page!
Contact Form
<!-- ***** Contact Form Start ***** -->
<div class="col-lg-8 col-md-6 col-sm-12">
<form action="{{ route('contacts') }}/send" method="POST">
#csrf
<div class="contact-form">
<div class="row">
<div class="col-lg-6 col-md-12 col-sm-12">
<input type="text" name="name" id="name" placeholder="Name">
</div>
<div class="col-lg-6 col-md-12 col-sm-12">
<input name="email" id="email" type="email" placeholder="E-Mail">
</div>
<div class="col-lg-12">
<textarea name="message" id="message" placeholder="Your message"></textarea>
</div>
<div class="col-lg-12">
<button type="send">Send message</button>
</div>
</div>
</div>
</form>
</div>
<!-- ***** Contact Form End ***** -->
But if I add {{json_decode ($ name)}} in file
contact-mail
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
name: {{ $name}} <br>
email: {{ $email}} <br>
message : {{$message }} <br>
</body>
</html>
The names are encoded with something like / u042 / u043 (but it's clear here, I encoded the name using json) and so on.
But the message field remains empty when receiving a letter.
Laravel 7.0
Sending email from localhost does not work. He writes that he cannot send a message without an email, but I put all the fields with emails. Created everything with docs.laravel.
App\Http\Controller\MailSetting
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;
use App\Mail\MailClass;
class MailSetting extends Controller
{
public function send_form(Request $request)
{
$name = $request->name;
$email = $request->email;
$message = $request->message;
Mail::to('test#mail.ru')->send(new MailClass($name, $email, $message));
}
}
App\Mail\MailClass
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MailClass extends Mailable
{
use Queueable, SerializesModels;
protected $name;
protected $email;
protected $message;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($name, $email, $message)
{
$this->name = $name;
$this->email = $email;
$this->message = $message;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.contact-mail')
->with([
'name' => $this->name,
'email' => $this->email,
'message' => $this->message,
])
->subject('New MESSAGE ');
}
}
I checked everything I could, but I never found an error

Change $message variable to another variable. Laravel automatically makes the $message variable available to all of your email templates

Related

Error 500 while trying to upload an image using FilePond and Laravel Spatie

I'm trying to create items that have a picture/avatar using a form and insert them into my database, so I decided to use Laravel Spatie with the MediaCollection, but as soon as i implemented the library, I'm getting an error 500 when I submit my form.... any idea why? And how am I supposed to create my database fields so when I create a new item with a picture I submit, the picture is submitted in a "Picture" datatable and in my "item" datatable I have the foreign key "picture_id" referencing to the picture in the Picture datatable.
Item.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Item extends Model implements HasMedia
{
use HasFactory;
use InteractsWithMedia;
public function inventory_list()
{
return $this->belongsTo(InventoryList::class);
}
public function work_ticket()
{
return $this->belongsToMany(WorkTicket::class);
}
public function picture()
{
return $this->belongsTo(Picture::class);
}
}
ItemController.php:
<?php
namespace App\Http\Controllers;
use App\Models\InventoryList;
use App\Models\Item;
use App\Models\Picture;
use App\Models\TemporaryFile;
use Illuminate\Http\Request;
class ItemController extends Controller
{
public function index()
{
$inventory_lists = InventoryList::all();
$pictures = Picture::all();
return view('add-item', ['inventory_lists' => $inventory_lists,
'pictures' => $pictures]);
}
public function store(Request $request)
{
$item = new Item;
$item->name = $request->name;
$item->state = $request->state;
$item->observations = $request->observations;
$item->list_id = $request->list_id;
$item->picture_id = $request->picture_id;
$temporaryFile = TemporaryFile::where('folder', $request->avatar)->first();
if($temporaryFile){
$item->addMedia(storage_path('app/public/avatars/tmp/' . $request->avatar . '/' . $temporaryFile->filename))
->toMediaCollection('avatars');
rmdir('app/public/avatars/tmp/' . $request->avatar);
$temporaryFile->delete();
}
$item->save();
return redirect('add-item')->with('status', 'Item Form Data Has Been inserted');
}
}
add-item.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Créer un nouvel item</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
#if(session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<div class="card">
<div class="card-header text-center font-weight-bold">
Ajouter un nouvel item
</div>
<div class="card-body">
<form name="add-blog-post-form" id="add-blog-post-form" method="post" action="{{url('store-item')}}">
#csrf
<div class="form-group">
<label for="name">Nom</label>
<input type="text" id="name" name="name" class="form-control" required="">
</div>
<div class="form-group">
<label for="state">État</label>
<input type="text" id="state" name="state" class="form-control" required="">
</div>
<div class="form-group">
<label for="observations">Observations</label>
<textarea name="observations" class="form-control" required=""></textarea>
</div>
<div class="form-group">
Liste d'inventaire
<select name="list_id" class="form-control select2-multiple">
<option value=""></option>
#foreach($inventory_lists as $inventory_list)
<option value="{{$inventory_list->id}}">
{{$inventory_list->name}}
</option>
#endforeach
</select>
</div>
<div>
<label for="avatar">Photo</label>
<input type="file" name="avatar" id="avatar">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#section('scripts')
<script>
const inputElement = document.querySelector('input[id="avatar"]');
const pond = FilePond.create( inputElement );
FilePond.setOptions({
server: {
url: '/upload',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
}
});
</script>
#endsection
</div>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
#yield('scripts')
</body>
</html>
UploadController.php
<?php
namespace App\Http\Controllers;
use App\Models\TemporaryFile;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function store(Request $request)
{
if ($request->hasFile('avatar')) {
$file = $request->file('avatar');
$filename = $file->getClientOriginalName();
$folder = uniqid() . '-' .now()->timestamp;
$file->storeAs('avatars/tmp/' . $folder, $filename);
TemporaryFile::create([
'folder' => $folder,
'filename' => $filename
]);
return $folder;
}
return '';
}
}
2022_05_06_063218_create_temporary_files_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('temporary_files', function (Blueprint $table) {
$table->id();
$table->string('folder');
$table->string('filename');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('temporary_files');
}
};
Thanks in advance
Edit:
I got this error right before getting my Error 500, then I simply refreshed my page and I never got the following error again, just an error 500.
local.ERROR: Declaration of
Spatie\MediaLibrary\MediaCollections\Models\Collections\MediaCollection::jsonSerialize()
must be compatible with
Illuminate\Support\Collection::jsonSerialize(): array
{"exception":"[object]
(Symfony\Component\ErrorHandler\Error\FatalError(code: 0):
Declaration of
Spatie\MediaLibrary\MediaCollections\Models\Collections\MediaCollection::jsonSerialize()
must be compatible with
Illuminate\Support\Collection::jsonSerialize(): array at
/home/vagrant/code/vendor/spatie/laravel-medialibrary/src/MediaCollections/Models/Collections/MediaCollection.php:51)
[stacktrace]
#0 {main}

Send email in laravel by using mailtrap

Hello this my project with laravel to send an email by using mailtrap
this is my sendemail controller
<?php
namespace App\Http\Controllers;
use App\Model\Sendemail;
use Illuminate\Http\Request;
use Mail;
use App\Mail\TestStarted;
class SendemailController extends Controller
{
public function start(Request $request)
{
$send_email = Mail::to($request->email)->send(new TestStarted);
if ($send_email)
{
return redirect()->back()->with('success', 'Sens email
successfully.');
}
}
}
and this function to share the approval student into studentcontroller
public function shareapproval($uniid)
{
$approval = Student :: where ('uniid', $uniid)->firstOrFail();
return view('SendEmail.Request.share',compact('approval'));
}
and this TestStarted.php in Mail file
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class TestStarted extends Mailable
{
use Queueable, SerializesModels;
public function build()
{
return $this->view('SendEmail.Request.mail');
return redirect()->back()->with('success', 'Sens email successfully.');
}
}
this is in config.mail.php
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'testgp2#system.com'),//
'name' => env('MAIL_FROM_NAME', 'Example'),
],
and this is my form to write the instructor email to send the email
#extends('layouts.app')
#section('content')
<div class="container">
<form method="post" action="/sendemail">
#csrf
<h1> send email </h1>
<br>
<<div class="form-group">
<label for="email">write the instructor email</label><br>
<input type="text" id="email" name="email" class="form-control" >
</div>
<button type="submit" class="btn btn-primary">send </button><br>
</form>
</div>
#endsection
and this is the content of mail I want to send it
this is mail.blade.php in (resources\views\SendEmail\Request\mail.blade.php)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-enguiv="X-UA-compatible" content="ie=edge">
<title>document </titel>
</head>
<body background-color: coral>
<h2> thank you for your order </h2>
</body
</html>
Finally, this is my route
Route::post('/student/share-approval/{uniid}',
'StudentController#shareapproval');
//SendEmail
Route::post('/sendemail','SendemailController#start');
Route::get('/start','SendemailController#start');
and I set up my .env with MAIL_USERNAME and MAIL_PASSWORD as shown in my account on mailtrap
Okay, let's start from the route. You're pointing the same method for the GET and POST request:
Route::post('/sendemail','SendemailController#start');
Route::get('/start','SendemailController#start');
As a result the mail field Mail::to($request->email) is getting null. Which could be a reason behind failure. So try to use different methods for handling GET and POST requests instead of one.
Route::get('/start','SendemailController#start');
Route::post('/sendemail','SendemailController#sendMail');
Secondly, in the code below, you are returning twice. But in real life it will only execute the first one and ignore the second one.
public function build()
{
// this is executing
return $this->view('SendEmail.Request.mail');
// this is getting ingorned
return redirect()->back()->with('success', 'Sens email successfully.');
}

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 5 Captcha by mewebstudio/captcha

Im running in laravel 5.2.* and I'm exploring the captcha validation in my new website. I saw a package in github naming mewebstudio/captcha. I followed his instruction for installation and testing if the image is working, it comes out fine but when im implementing it in my login page, I got little confused where should i declare the validation.
I inputted the login credentials and I tried to not input the correct answer in the captcha box and surprisingly, i got in to the home page which should be not. Do you guys have any solutions for this? thanks.
P.S. Sorry for my english
Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LOGIN</title>
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">
<meta name="theme-color" content="#ffffff">
</head>
<body>
<div id="wrap">
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-4 col-xs-offset-0 col-sm-offset-1 col-md-offset-4">
<div class="main-content-login">
<div class="panel panel-fos" style="margin-top: 100px;">
<div class="panel-heading">
<h3> LOG IN</h3>
</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul style="text-align: left;">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form id="emailForm" role="form" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<!--<div class="row">
<div class="col-sm-4 col-lg-3">
<label>Username:</label>
</div>
<div class="col-sm-8 col-lg-9">
<input type="password" name="password" class="form-control login" id="password">
</div>
</div>-->
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-user"></span>
<input type="email" id="email" name="email" class="form-control" aria-describedby="inputGroupSuccess3Status" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-lock"></span>
<input type="password" class="form-control" id="password" name="password" aria-describedby="inputGroupSuccess3Status" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="input-group">
{!! captcha_img() !!}
<input type="text" name="captcha" id="captcha">
</div>
</div>
<div class="row" style="margin-top: 30px;">
<div class="col-xs-12 col-sm-6">
<input type="submit" class="btn btn-md btn-primary btn-move-right login-btn" value="Log In"> </button>
</div>
<div class="col-xs-12 col-sm-6 checkbox remember" style="margin-top: 0;">
<label class="remember"><input type="checkbox"> Remember me</label>
</div>
</div>
<div class="row">
<div class="col-xs-12">
Forgot Password?
</div>
</div>
{{--<div class="row" style="margin-top: 30px;">
<div class="col-xs-7 col-lg-7">
<input type="submit" class="btn btn-md btn-primary btn-move-right" value="Log In"> </input> <span class="login"><a href="#" > Forgot Password?</a></span>
</div>
<div class="col-xs-5 col-lg-5 checkbox text-right" style="margin-top: 0;">
<label class="remember"><input type="checkbox" name="remember" value="{{old('remember')}}"> Remember me</label>
</div>
</div>--}}
</form>
</div>
</div>
<p class="text-center">An INF-SRD Project. All Rights Reserved 2015.</p>
</div>
</div>
</div>
</div>
</div>
<!--END OF WRAPPER-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="<?php echo asset('js/bootstrap.min.js');?>"></script>
</body>
</html>
Controller:
(AuthController.php)
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\View\Middleware\ErrorBinder;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
private $redirectTo = '/';
private $maxLoginAttempts = 10;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* 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|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
(AuthenticatesUsers.php)
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function getLogin()
{
return $this->showLoginForm();
}
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
if (property_exists($this, 'loginView')) {
return view($this->loginView);
}
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('auth.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
return $this->login($request);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required','captcha'=>'required',
]);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Get the failed login message.
*
* #return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password');
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
return $this->logout();
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function loginUsername()
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* #return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(get_class($this))
);
}
/**
* Get the guard to be used during authentication.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
can check this package better for recaptcha
https://github.com/anhskohbo/no-captcha
you can check recapcha in validation rules
In Your Package can check in rules for example
$rules = ['captcha' => 'required|captcha'];
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
echo '<p style="color: #ff0000;">Incorrect!</p>';
}
else
{
echo '<p style="color: #00ff30;">Matched :)</p>';
}

Laravel 5.1 Login Controller Doesnt Work Well

I'm new to laravel. I have a problem with my login control where I can't match the data from my form and the database.
The error message said :
DecryptException in BaseEncrypter.php line 45: The payload is invalid.
Controller
namespace App\Http\Controllers;
use DB;
use Hash;
use Crypt;
use Validator;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class LoginControl extends Controller
{
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required',
'password' => 'required',
]);
if ($validator->fails()) {
return redirect('/login')
->withErrors($validator)
->withInput();
}
else{
$email = $request->email;
$password = $request->password;
$results = DB::select('select * from users where email = ? and password = ?', [$email,$password]);
$pass = Crypt::decrypt($request->password);
if($results == NULL){
return redirect('/login');
}
else{
return redirect('/');
}
}
}
}
Router
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/register', function () {
return View::make('register');
});
Route::get('/login', function() {
return View::make('login');
});
Route::post('actionregis', 'RegisControl#store');
Route::post('actionlogin', 'LoginControl#login');
View
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<title>Laravel Quickstart - Basic</title>
<!-- CSS And JavaScript -->
</head>
<body>
<div class="container">
<nav class="navbar navbar-default">
<!-- Navbar Contents -->
</nav>
</div>
<div class="panel-body">
<div class="col-md-8 col-md-offset-2">
<!-- New Task Form -->
<form action="/testing/public/actionlogin" method="POST" class="form-horizontal">
{{ csrf_field() }}
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Task Name -->
{!! csrf_field() !!}
<div class="form-group">
<label for="user">Email</label>
<input type="text" name="email" id="task-email" class="form-control">
</div>
<div class="form-group">
<label for="user">Password</label>
<input type="password" name="password" id="task-password" class="form-control">
</div>
<div class="form-group">
<input type="checkbox" name="remember"> Remember Me
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Login</button>
</div>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
You are decrypting an unecrypted string (this is why you are getting the error):
$pass = Crypt::decrypt($request->password);
Why is this even here? $pass is not doing anything.
As of now, you are searching for a user with an unecrypted password.
To check if the password is valid, you do NOT decrypt the password in DB, you encrypt the inserted one and see if they match.
How are you encrypting the password when inserting it?
Laravel provides a mostly-done authentication by default, you should use it if you don't know what you are doing and want to have authentication as secure as possible. Read about it here: http://laravel.com/docs/5.0/authentication
To write your own authentication, you should use the Hash class:
$password = Hash::make('some_password'); // Use this to hash your password (you can store that in the DB)
// To check the password, you parse the user's hashed password from the DB
... // <- parse user here
$hashedPassword = $user->password;
// Password checking
if (Hash::check('some_password', $hashedPassword))
{
// The passwords match...
}
Since you have a lot of data maybe the column type in your database is too small and you are therefore getting this error.
Try to set the column to longtext instead of text in your migration and see if that works.

Categories