I am attempting to send mail from a Laravel app but can't quite get it to work. I have an email address set up on the server through cPanel and would like to be able to send from that email in Laravel.
In Codeigniter I could simply leave the config file empty like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = Array(
'protocol' => '',
'smtp_host' => '',
'smtp_port' => '',
'smtp_user' => '',
'smtp_pass' => '',
'mailtype' => '',
'starttls' => true,
'newline' => "\r\n"
);
And send using a script like this:
$this->load->library('email');
$this->email->from('email#gmail.com', 'Test Person');
$this->email->to('test#hotmail.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
What is the equivalent set up in Laravel? I can't leave the SMPT host blank or it throws an error. If I change the driver to 'mail', and leave everything else blank, it will not throw an error but I will not receive an email.
Here is the Laravel mail config for good measure:
<?php
return array(
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill", "log"
|
*/
'driver' => 'mail',
/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/
//'host' => 'smtp.mailgun.org',
'host' => '',
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/
//'port' => 587,
'port' => '',
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => array('address' => null, 'name' => null),
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => '',
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
//'username' => null,
'username' => '',
/*
|--------------------------------------------------------------------------
| SMTP Server Password
|--------------------------------------------------------------------------
|
| Here you may set the password required by your SMTP server to send out
| messages from your application. This will be given to the server on
| connection so that the application will be able to send messages.
|
*/
//'password' => null,
'password' => '',
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
/*
|--------------------------------------------------------------------------
| Mail "Pretend"
|--------------------------------------------------------------------------
|
| When this option is enabled, e-mail will not actually be sent over the
| web and will instead be written to your application's logs files so
| you may inspect the message. This is great for local development.
|
*/
'pretend' => false,
);
Related
Try to implements a custom user class in Laravel JWT authentication
I'm trying to implement an application that use a custom table for the user's informations.
My table _user looks like that
'USR_NoRole',
'USR_CompleteName',
'USR_UserName',
'USR_Password',
'USR_BBlocked',
'USR_BAssociation',
'USR_NoPeriode',
'USR_NoEntite',
'USR_CreateUser',
'USR_CreateTimestamp',
'USR_UpdateUser',
'USR_UpdateTimestamp'
When i create a new user, everything works and i get back a token
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'noRole' => 'required',
'completeName' => 'required',
'name' => 'required|string|max:255',
'password' => 'required|string|min:6|confirmed',
'noPeriode' => 'required',
'noEntite' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create([
'USR_NoRole' => $request->get('noRole'),
'USR_CompleteName' => $request->get('completeName'),
'USR_UserName' => $request->get('name'),
'USR_Password' => Hash::make($request->get('password')),
'USR_BBlocked' => $request->get('isBlocked'),
'USR_BAssociation' => $request->get('isAssociation'),
'USR_NoPeriode' => $request->get('noPeriode'),
'USR_NoEntite' => $request->get('noEntite'),
'USR_CreateUser' => "jschneider",
'USR_CreateTimestamp' => date("Y-m-d H:i:s"),
'USR_UpdateUser' => "jschneider",
'USR_UpdateTimestamp' => date("Y-m-d H:i:s"),
]);
$token = JWTAuth::fromUser($user);
return response()->json(compact('user', 'token'), 201);
}
Here the result
{
"user": {
"USR_NoRole": "1",
"USR_CompleteName": "Complete Name",
"USR_UserName": "test#test.com",
"USR_Password": "$2y$10$bli2OTQQfsq7h4/XryZT4Op4p5DCnEGANCR5MYagHbndNU/ULmE3G",
"USR_BBlocked": null,
"USR_BAssociation": null,
"USR_NoPeriode": "1",
"USR_NoEntite": "1",
"USR_CreateUser": "test",
"USR_CreateTimestamp": "2019-04-01 07:02:13",
"USR_UpdateUser": "test",
"USR_UpdateTimestamp": "2019-04-01 07:02:13",
"id": 3
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL2xhcmF2ZWwtand0XC9wdWJsaWNcL2FwaVwvcmVnaXN0ZXIiLCJpYXQiOjE1NTQxMDIxMzQsImV4cCI6MTU1NDEwNTczNCwibmJmIjoxNTU0MTAyMTM0LCJqdGkiOiJ2UGFURmNVbFE2WHVSY251Iiwic3ViIjozLCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.Vi75d8uVSpzR_VddgfhJVGcyaNd-MsvjazPuUy81RXg"
}
But after that, when i try to login with this new user, i can't get a token. The result is always :
{
"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'where clause' (SQL: select * from `_user` where `name` = jschneider#patinfo.ch limit 1)",
}
How can i configure the credentials to say that the field name matches with USR_UserName and the field password matches with USR_Password ?
My custom user class
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $table = '_user';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'USR_NoRole', 'USR_CompleteName', 'USR_UserName', 'USR_Password', 'USR_BBlocked', 'USR_BAssociation', 'USR_NoPeriode', 'USR_NoEntite', 'USR_CreateUser', 'USR_CreateTimestamp', 'USR_UpdateUser', 'USR_UpdateTimestamp'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
// 'email_verified_at' => 'datetime',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
the config/auth.php file
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Can anyone explain me how to set the app and create a token based on this 2 fields ?
place it on your controller
Config::set('jwt.user', 'App\OtherMOdel'); Config::set('auth.providers.users.model', \App\OtherMOdel::class);
I am using JWT in lumen and am unable to get token without password only With Email and i am using this code form stack overflow --
$user=User::where('email','=','user2#gmail.com')->first();
if (!$userToken=JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
return response()->json(compact('userToken'));
This code give me error like this ->
ErrorException in UserController.php line 44:
Non-static method Tymon\JWTAuth\JWT::fromUser() should not be called statically, assuming $this from incompatible context
My controller UserController.php -
namespace App\Http\Controllers\v1;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Exception;
use Cartalyst\Sentinel\Native\Facades\Sentinel;
use Cartalyst\Sentinel\Laravel\Facades\Activation;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Support\Facades\Mail;
use App\Model\User;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
My - Config/auth
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'api'),
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'identifier' => 'email',
'password' => 'password',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
//
],
];
My bootstrap/app
<?php
require_once __DIR__ . '/../vendor/autoload.php';
try {
(new Dotenv\Dotenv(__DIR__ . '/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
//
}
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__ . '/../')
);
$app->withFacades();
$app->configure('jwt');
$app->configure('auth');
class_alias(Tymon\JWTAuth\Facades\JWTAuth::class, 'JWTAuth');
class_alias(Tymon\JWTAuth\Facades\JWTFactory::class, 'JWTFactory');
$app->withEloquent();
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Routing\ResponseFactory::class,
Illuminate\Routing\ResponseFactory::class
);
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
// $app->middleware([
// App\Http\Middleware\ExampleMiddleware::class
// ]);
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'jwt.auth' => Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => Tymon\JWTAuth\Middleware\RefreshToken::class,
]);
/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(App\Providers\EventServiceProvider::class);
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
require __DIR__ . '/../app/Http/routes.php';
});
return $app;
My Model User -
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements JWTSubject, AuthenticatableContract, AuthorizableContract {
use Authenticatable,
Authorizable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password',
];
public function getJWTIdentifier() {
return $this->getKey();
}
public function getJWTCustomClaims() {
return [];
}
}
My - JwtSubject -
<?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148#gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Contracts;
interface JWTSubject
{
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier();
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims();
}
My function __construct
class UserController extends Controller {
public $request;
protected $jwt;
public function __construct(Request $request, JWTAuth $jwt) {
try {
$this->request = $request;
$this->jwt = $jwt;
} catch (Exception $ex) {
\Log::error("Error : " . $ex);
$output = array('success' => false, 'result' => null, 'error' => $ex, 'error_key' => 'unhandled_exception');
return new Response($output);
}
}
Please help me how can i get token using only Email.
The issue is caused by this use statement in your UsersController.
use Tymon\JWTAuth\JWTAuth;
When you call JWTAuth::fromUser($user) you are not referencing the Facade (that contains an instance of JWTAuth already) but the actual function of the class, which you can't because it's not called statically.
This is what builds the Facade:
class_alias(Tymon\JWTAuth\Facades\JWTAuth::class, 'JWTAuth');
Remove that use statement and you should be fine.
Or modify it to use JWTAuth; so that you're referencing properly the Facade that is globally accessible.
I have configured config/mail.php, controllers,etc. still not working and throwing this error:
[2015-12-05 14:47:57] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Swift_Mailer' not found' in /vdir/www.adfusion.ch/var/www/vhosts/www.adfusion.ch/web/laravel/vendor/laravel/framework/src/Illuminate/Mail/MailServiceProvider.php:95
Stack trace:
#0 {main}
My contact controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
class ContactController extends Controller
{
public function index()
{
return view('contact');
}
public function postSubmit(Request $request)
{
Mail::send('emails.contact', ['data' => $request->all()], function ($m) {
$m->from(config('mail.from.address'), config('mail.from.name'));
$m->to('info#xxxxx', 'xxxx')->subject('Contact Form Submitted');
});
}
}
Routes:
Route::get('/contact', 'ContactController#index');
Route::post('/contact/submit', 'ContactController#postSubmit');
I have a emails/contact view. is there anything that I missed?!
EDIT:
Mail configuration file:
return [
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill", "ses", "log"
|
*/
'driver' => 'smtp',
/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/
'host' => 'smtp.XXXX',
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/
'port' => 25,
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => ['address' => 'no-reply#XXX', 'name' => 'XX'],
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => null,
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
'username' => 'no-reply#XXXX',
/*
|--------------------------------------------------------------------------
| SMTP Server Password
|--------------------------------------------------------------------------
|
| Here you may set the password required by your SMTP server to send out
| messages from your application. This will be given to the server on
| connection so that the application will be able to send messages.
|
*/
'password' => 'XXXXX',
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
/*
|--------------------------------------------------------------------------
| Mail "Pretend"
|--------------------------------------------------------------------------
|
| When this option is enabled, e-mail will not actually be sent over the
| web and will instead be written to your application's logs files so
| you may inspect the message. This is great for local development.
|
*/
'pretend' => false,
];
Marked username and domain name with XXX
Why does it uses swift? I'm trying to use the hosting mail server
tried a dd in the controller, it does nothing! why does not gets to the contact controller?
contact view:
<form role="form" id="feedbackForm" data-toggle="validator" data-disable="false" method="POST" action="{{ url('contact/submit') }}">
also, on local server, if I set pretend to true, I get in log the following:
[2015-12-05 16:49:50] local.INFO: Pretending to mail message to: info#xxxx
This is the server log:
[Sat Dec 05 17:56:29 2015] [warn] [client 188.24.47.222] mod_fcgid: stderr: PHP Fatal error: Class 'Swift_Transport_EsmtpTransport' not found in /vdir/www.xxx.ch/var/www/vhosts/www.xxx.ch/web/laravel/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php on line 24, referer: http://xxx.ch/contact
Have you changed your mail driver, host etc in your environment variables (.env) file?
Here:
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
These must be set to the same as your username and password etc. in your mail config file
Yes, of course. Here's the solution that I used in order to configure email for laravel.
indexmail.php, root folder
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="your-email#your-domain.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
else
header("Location:../contact.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
?>
routes.php
Route::post('/contact/submit', 'ContactController#postSubmit');
config/mail.php
'from' => ['address' => 'Sender#email.com', 'name' => 'MyName'],
'pretend' => false,
email view.
<strong>You have a new feedback from contact page!</strong>
<p><strong>Name: </strong> {{$data['name']}}</p>
<p><strong>Email: </strong> {{$data['email']}}</p>
<p><strong>Message: </strong> {{$data['message']}}</p>
contact form.
<form role="form" id="feedbackForm" data-toggle="validator" data-disable="false" method="POST"
action="{{ url('contact/submit') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}"/>
app/Http/Requests/ContactFormRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ContactFormRequest extends Request
{
/**
* 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',
'email' => 'required|email',
'message' => 'required',
];
}
}
app/User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Let me know if it works!
I'm working on a Laravel Project which using a Postgre database, I run
php artisan migrate
Then I get error
[PDPException] could not find driver
But all my drivers is properly installled and enabled in my php.ini . I have a Yii Application that uses Postgre and works fine. php_pdo_pgsql is already installed and enabled.
Here's my config on Laravel
<?php
return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => 'pgsql',
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => storage_path('database.sqlite'),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => '192.168.3.9',
'database' => 'qms',
'username' => 'postgres',
'password' => 'postgres',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'cluster' => false,
'default' => [
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
],
],
];
You will need the doctrine/dbal package to use postgres. https://packagist.org/packages/doctrine/dbal
Add this to your application by requiring the package:
composer require doctrine/dbal
Good morning fellow devs please i am working on login authentication on my app
but i want to do a validation on the login credentials. so this what i did and this are my errors. In my models/ directory
class Login Extends Eloquent
{
protected $table = 'pb_user';
}
then in my auth.php
<?php
return array(
/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/
'driver' => 'eloquent',
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
'model' => 'Login',
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
'table' => 'pb_user',
/*
|--------------------------------------------------------------------------
| Password Reminder Settings
|--------------------------------------------------------------------------
|
| Here you may set the settings for password reminders, including a view
| that should be used as your password reminder e-mail. You will also
| be able to set the name of the table that holds the reset tokens.
|
| The "expire" time is the number of minutes that the reminder should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
then this my LoginController.php for login
class LoginController extends BaseController {
/*
|--------------------------------------------------------------------------
| Default Home Controller
|--------------------------------------------------------------------------
|
| You may wish to use controllers instead of, or in addition to, Closure
| based routes. That's great! Here is an example controller method to
| get you started. To route to this controller, just add the route:
|
| Route::get('/', 'HomeController#showWelcome');
|
*/
public function get_login_data()
{
$pb_login_email=Input::get('pb-login-email');
$pb_login_password=Input::get('pb-login-pass');
$date_reg=date('Y-m-d');
$time_reg=date('r');
/* hashed the password */
$pb_login_password_hashed = Hash::make($pb_login_password);
/* encrypt the email and password */
$pb_login_email_crypted = Crypt::encrypt($pb_login_email);
/* validate if the user has has an account */
// goto the database first and get the data before authenticating
// because of the diffrent type of hash....
/*$pb_login_email=DB::table('pb_user')->where('email', 'udemesamuel256#gmail.com')->first();
$users = DB::table('pb_user')
->where('email', '=', $pb_login_email_crypted)
->get();
var_dump($users->email);*/
if (Auth::attempt(array('email' => $pb_login_email, 'password' => $pb_login_password)))
{
return Redirect::to('http://facebook.com');
}
else
{
return Login::all();
}
}
}
this is the error.
ErrorException
Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Auth\UserInterface, instance of Login given, called in /var/www/laravel4/vendor/laravel/framework/src/Illuminate/Auth/Guard.php on line 370 and defined
Then when i tried to remove the table property from the login class :
class Login Extends Eloquent
{
//protected $table = 'pb_user';
}
the error is:
Illuminate \ Database \ QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'popibay.logins' doesn't exist (SQL: select * from `logins` where `email` = theresasamuel#gmail.com limit 1)
Note : please support your answers with examples and links for quick understanding.
This is due to the fact that Laravel expects the model you use for Auth to implement the UserInterface. This is as simple as class Login extends Eloquent implements UserInterface {
However you now have to implement the methods in UserInterface. If you take a look at Illuminate\Auth\UserInterface you will see these are:
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier();
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword();
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken();
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value);
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName();
You can see how these are implemented in the User model supplied by Laravel.