Cannot send message without a sender address Error in laravel - laravel

I'm trying to send raw mail but I;m getting an error "Cannot send message without a sender address" and I don't seem to see where I'm going wrong. I've provided the sender email in the .env file but it's still giving that error
My Controller!
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
class ContactController extends Controller
{
public function show()
{
return view('user.contact');
}
public function store()
{
request()->validate(['email' => 'required|email']);
Mail::raw('it works', function ($message) {
$message->to(request('email'))
->subject('Hi There');
});
return redirect()->back();
}
}
My .env file
MAIL_MAILER=log
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=admin#example.com
MAIL_FROM_NAME="${APP_NAME}"
My mail.php file
<?php
return [
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
],
'postmark' => [
'transport' => 'postmark',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
],
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];
My form!
<form action="{{ route('contact')}}" method="post">
#csrf
<div class="form-group">
<label>E-mail</label>
<input type="email" name="email" class="form-control">
#error('email')
<p style="color: red; font-size: 15px; margin-top: 5px">{{ $message }}</p>
#enderror
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I'm trying to send raw mail but I;m getting an error
Cannot send message without a sender address
and I don't seem to see where I'm going wrong. I've provided the sender email in the .env file but it's still giving that error

In your env file your username and password are null, you should be able to take the username and password from mailtrap, and it should work

Try this, it should work :
public function store(Request $request)
{
$this->validate($request, [
'email' => 'required|email'
]);
$email = $request->email;
$data = [
'email' => $request->email,
];
Mail::send('mail', $data, function ($message) use ($email) {
$message->to('myemail#gmail.com', 'Email Title')->subject('Test Subject 2');
$message->from($email, "Sender Name");
});
echo "HTML Email Sent. Check your inbox.";
}

When the configuration is cached the .env file no longer gets loaded. Instead Laravel uses the cached configuration so that the app loads quicker.
So when change .env file it is a good idea to run php artisan config:cache.

You need to clear cache in order to prevent this error . use the following commands one by one and your error will be solved .
- php artisan cache:clear
- php artisan route:cache
- php artisan view:clear
- php artisan config:cache
Hope it helped you .

Related

Auth with Laravel Sanctum and JWT Token

this is my controller
public function logout()
{
auth()->logout();
return redirect()->route('home');
}
this is my auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
and this is my logout form in blade.php file
<form action="{{ route('logout') }}" method="post"> #method('POST') #csrf <button>logout</button> </form>
i wrote my logout request on api.php
Route::middleware(['auth:sanctum', 'verified'])->group(function () {
Route::post('logout', [AuthController::class, 'logout'])->name('logout');
});
my other method (login , register and show userpage) works but only logout doesn't work.
my logout page redirect to api/login url and it says GET method not allowed here. Only POST method.
this is my full controller code
https://github.com/sksmsWKd/MetaComposerProto/blob/master/app/Http/Controllers/AuthController.php

Laravel and Mailgun

I am trying to set up emailing feature on my laravel project. I got everything settled up but somehow I get this error
Swift_TransportException
Cannot send message without a sender address.
Here is my mail.php script.
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
],
'mailgun' => [
'transport' => 'mailgun',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
],
.env file
MAIL_MAILER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=2525
MAIL_USERNAME=postmaster#sandbox*****************.mailgun.org
MAIL_PASSWORD=**********************************
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
ReportInfrastructure.php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ReportInfrastructure extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('infor#mise.gov.ki')
->markdown('emails.infrastructure');
}
}
infrastructure.blade.php
#component('mail::message')
# Critical Infrastructure Name
PLEASE NOTE: You're receiving this email because our records indicate that above Infrastructure is in critical condition and need to address asap.
Click the on the button below to show more details of this issue.
#component('mail::button', ['url' => ''])
Button Text
#endcomponent
Thanks,<br>
{{ config('app.name') }}
#endcomponent
Route
Route::get('/email', function () {
Mail::to('email#email.com')->send(new ReportInfrastructure());
return new ReportInfrastructure();
});
Can someone point me out what I did wrong?

How to reset password for admin with different table in laravel 5.6?

I have installed fresh laravel and copy all the login,register and password views and contorller for admin login and created table called 'admins'. When i tried to reset the password for laravel default user it works but for 'admins' user it doesn't update the password. And the password resets table is also empty when the default user password is reset.
// providers in config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Dashboard\Admin::class,
],
],
// passwords reset in config/auth.php
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'admin_password_resets',
'expire' => 60,
],
],
//Also added broker and guard in ResetPasswordController.php
public function broker()
{
return Password::broker('admins');
}
protected function guard()
{
return Auth::guard('admin');
}
All i want is to update the admin password and filled the users_reset_table when password is reset. How can i achieve this??
Step 1: Update auth.php
// Providers in config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\models\Admin::class,
]
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
Setp 2:
Add two functions in ForgotPasswordController.php
/**
* Get the broker to be used during password reset.
*
* #return PasswordBroker
*/
protected function broker()
{
return Password::broker('admins');
}
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\View\View
*/
public function showLinkRequestForm()
{
return view('auth.passwords.email')->with('user_type', request()->user_type);
}
Setp 3:
Add two functions in ResetPasswordController.php
/**
* Get the broker to be used during password reset.
*
* #return PasswordBroker
*/
protected function broker()
{
return Password::broker('admins');
}
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* #param \Illuminate\Http\Request $request
* #param string|null $token
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email, 'user_type' => $request->user_type]
);
}
Setp 4:
//Sending user-type on Blade Template
//admin-show.blade.php from where I want to reset password.
<button class="btn btn-primary btn-sm" onclick="event.preventDefault();
document.getElementById('change-password-form').submit();">
<span class="fa-passwd-reset">
<i class="fa fa-lock"></i>
</span> </i> Change Password
</button>
<form id="change-password-form" method="POST"
action="{{ route('password.email', ['user_type' => 'admin']) }}">
#csrf
<input type="hidden" name="email" value="{{ $admin->email }}">
Setp 5: //Now open email.blade.php and reset.blade.php inside views/auth/passwords/ and add an hidden input field like so
<input type="hidden" name="user_type" value="{{ $user_type }}" required>
Source: https://medium.com/backenders-club/password-brokers-reset-passwords-on-multiple-tables-in-laravel-73068542925c
Did you add the table in your App\Dashboard\Admin Model?
protected $table = 'admins';
As far as I know, you need to overwrite some methods in Auth\ResetPasswordController.php
By the looks of the file, I have a feeling that those two methods should be overwritten.
protected function guard()
{
return Auth::guard('owner');
}
public function broker()
{
return Password::broker('admin');
}
Resetting Passwords for admins table particularly
Laravel includes Auth\ForgotPasswordController and Auth\ResetPasswordController classes that contains the logic necessary to e-mail password reset links and reset user passwords. All of the routes needed to perform password resets may be generated using the laravel/ui Composer package:
run the below commands:
php artisan make:notification ResetPasswordNotification
composer require laravel/ui
php artisan ui vue --auth
and
copy auth folder from resources\views and named admin
Step 1: customize the config/auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
// Admin guards
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Setp 2: ForgotPasswordController.php in App\Http\Controllers\Admin Folder
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Support\Facades\Password;
class ForgotPasswordController extends Controller
{
use SendsPasswordResetEmails;
public function showLinkRequestForm()
{
return view('admin.passwords.email');
}
public function __construct()
{
$this->middleware('guest:admin');
}
public function broker()
{
return Password::broker('admins');
}
}
And
ResetPasswordController.php in App\Http\Controllers\Admin Folder
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
class ResetPasswordController extends Controller
{
use ResetsPasswords;
protected $redirectTo = 'admin/dashboard';
public function showResetForm(Request $request, $token = null)
{
return view('admin.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
public function __construct()
{
$this->middleware('guest:admin');
}
public function broker()
{
return Password::broker('admins');
}
}
Setp 3: Admin.php Model in App Folder
Reset Email Customization
You may easily modify the notification class used to send the password reset link to the user. To get started, override the sendPasswordResetNotification method on your User model. Within this method, you may send the notification using any notification class you choose. The password reset $token is the first argument received by the method:
<?php
namespace App;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
}
Setp 4: web.php route file in routs Folder
Route::get('admin-login','Admin\LoginController#showLoginForm')->name('admin.login');
Route::post('admin-password/email','Admin\ForgotPasswordController#sendResetLinkEmail')->name('admin.password.email');
Route::get('admin-password/reset','Admin\ForgotPasswordController#showLinkRequestForm')->name('admin.password.request');
Route::post('admin-password/reset','Admin\ResetPasswordController#reset')->name('admin.password.update');
Route::get('admin-password/reset/{token}','Admin\ResetPasswordController#showResetForm')->name('admin.password.reset');
Setp 5: email.blade.php file in resources\views\admin\passwords Folder
<form method="POST" action="{{ route('admin.password.email') }}">
in reset.blade.php file in resources\views\admin\passwords Folder
<form method="POST" action="{{ route('admin.password.update') }}">
and login.blade.php file in resources\views\admin Folder
<form method="POST" action="{{ route('admin.login') }}">
Setp 6: ResetPasswordNotification.php file in app\Notifications Folder
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Lang;
class ResetPasswordNotification extends Notification
{
use Queueable;
public $token;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject(Lang::get('Reset Password Notification'))
->line(Lang::get('You are receiving this email because we received a password reset request for your account.'))
->action(Lang::get('Reset Password'), url(config('app.url').route('admin.password.reset', ['token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset()], false)))
->line(Lang::get('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]))
->line(Lang::get('If you did not request a password reset, no further action is required.'));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Source: https://medium.com/backenders-club/password-brokers-reset-passwords-on-multiple-tables-in-laravel-73068542925c

Add barryvdh/laravel-ide-helper for Laravel to PhpStorm

I add the barryvdh/laravel-ide-helper plugin into PhpStorm 2017.3.4 for Laravel 5.6. It seems that it does not work properly.
routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Method 'middleware' not found in Route
routes/web.php
Route::get('/', function () {
return view('welcome');
});
This one is ok
routes/channels.php
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Method 'channel' not found in Broadcast
App\Http\Controllers\Auth\RegisterController.php
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',
]);
}
Multiple definitions exist for class Validator
config/app.php
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Debugbar' => Barryvdh\Debugbar\Facade::class,
],
Multiple definitions exist for class App.Multiple definitions exist for class Artisan. All lines show these info.
What should I do? I just begin to learn to use Laravel.
You need to run the following artisan commands:
php artisan ide-helper:generate
php artisan ide-helper:models
php artisan ide-helper:meta
In fact I recommend to include it in the post-update-cmd part of your composer.json file so it runs these commands automatically everytime your do composer update
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"#php artisan ide-helper:generate --tenant=tda",
"#php artisan ide-helper:meta --tenant=tda",
"#php artisan horizon:publish --ansi --tenant=tda",
]

Laravel 5.2: Session store not set on request. Error for Blade Templates with old()

I am testing with PHPUnit 4.0, Laravel 5.2, PHP 5.5.9, and keep getting the error ERROR: exception 'RuntimeException' with message 'Session store not set on request.' in /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Request.php:85
To rule it out, middleware is enabled.
If I remove {{ old('username') }} from the form, the error goes away. I have seen several posts in regards to this issue using the old() method; however, I have updated the kernel.php, moved the route under a middleware group to reference 'web', even moved start session to the default middleware array() in kernel.php. I have also, tried calling the session from TestCase.php. None of the forums seem to have a working solution. Is there something I'm missing in the syntax, or is there a bug in Laravel?
My kernel.php file looks like
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'sso' => \App\Http\Middleware\SsoEnabled::class
];
}
My signup.blade.php looks like:
#extends('layouts.main')
#section('body')
<body>
<h2>Signup</h2>
<form class="m-t" role="form" method="POST" action="/signup">
<div class="form-group">
<input name="username" type="text" placeholder="Username" value="{{ old('username') }}" required="">
</div>
<button type="submit" name="Signup" >Signup</button>
</form>
</body>
#endsection
My routes.php looks like:
<?php
Route::group(['middleware' => ['web']], function () {
Route::group(array('middleware' => ['sso:0']), function ($key) {
Route::get('signup/{token}', [
'as' => 'customer.signup',
'uses' => 'SignupController#getApplication'
]);
});
});
I have even tried adding a new block to the testCase.php setUp without any luck:
$this->app['config']->set('session', [
'driver' => 'array',
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => false,
'lottery' => [2, 100],
'path' => '/',
'domain' => 'localhost',
'secure' => true,
'email' => 'email#email.com',
'store' => 'storage'
]);
$kernel = app('Illuminate\Contracts\Http\Kernel');
$kernel->pushMiddleware('Illuminate\Session\Middleware\StartSession');
Not sure it's the best solution, but I managed to get it working properly by setting session store in setUp().
\Illuminate\Support\Facades\Request::setSession($this->app['session.store'])

Resources