Send emails in laravel from a web server - laravel

I have a Laravel project that I need to send emails to, and it works on localhost, but when I upload it to a web server it doesn't work. Where's my mistake?
Controller:
class merluzaController extends Controller
{
public function mail(request $request){
$datos=[
"nombre"=>$request->nombre,
"apellido"=>$request->apellido,
"correo"=>$request->correoE,
"numeroT"=>$request->numeroT,
"mensaje"=>$request->mensaje,
];
Mail::send('emails.mails', $datos, function ($message) {
$message->to("ltomicb#gmail.com", "Lucas")->subject('Página de MerluzaDePincho');
});
Session::flash('mensaje_enviado','Mensaje enviado correctamente.');
return redirect('/contacto');
}
}
ENV:
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=postmaster#sandbox8f7345b6f0f14762871d8489a6a672c9.mailgun.org
MAIL_PASSWORD=****************
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=merluzadepincho#gmail.com
MAIL_FROM_NAME="Merluza de Pincho"

if the problem is "Class 'Illuminate\Support\facades\Mail' not found then you have to import it
you can try to use
use Illuminate\Support\Facades\Mail;
or you can try
\Mail::send('emails.mails', $datos, function ($message) {
$message->to("ltomicb#gmail.com", "Lucas")->subject('Página de MerluzaDePincho');
});
instead of
Mail::send('emails.mails', $datos, function ($message) {
$message->to("ltomicb#gmail.com", "Lucas")->subject('Página de MerluzaDePincho');
});
as \Mail::send() doesn't need to be imported
you can check this article you can find here some good answers
if nothing of this works then you need to verify that guzzle package is configured correctly and its version is 6 higher and look into your server php modules and compare them to your dev modules php -m should list them all
finally reach out to your hosting company and explain the issue for them as some companies block this kind of callbacks for security reasons or to force the user to purchase a premium account or something like that
hope this helps.

Related

Kreait\Firebase\Exception\Database\DatabaseError 404 Not Found

I am new to Laravel so i have been trying to connect Laravel to a Firebase Realtime database but i am getting this error Kreait\Firebase\Exception\Database\DatabaseError
404 Not Found . I have the Service account in the controllers directory and properly referenced in the Firebase controller.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Database;
class FirebaseController extends Controller
{
$factory = (new Factory)->withServiceAccount(__DIR__.'/myServiceAccount.json');
$database = $factory->createDatabase();
$newPost = $database->getReference('myrealtime-default-rtdb/blog/posts')->push(['title' => 'Post title','body' => 'This should probably be longer.']);
echo"<pre>";
print_r($newPost->getvalue());
}
}
}
Using the new Factory pattern won't work (it's already handled by the Laravel Service Provider).
Personally I'd recommend using the app() helper. It's quite easy but before that make sure you've followed the installation process in the documentation. You might've missed something
Here's a link to that: https://github.com/kreait/laravel-firebase
Also make sure you include both the path to your Service Account json file and the database URL for your project in your .env file (I prefer using this method personally)
So in your .env file you should have something like
FIREBASE_CREDENTIALS = path_to_your_service_account_file.json
FIREBASE_DATABASE_URL= https://your-project-url.firebaseio.com/
(you can find this url when you open RealTime databases in your firebase console)
If you don't use auto-discovery make sure to add Kreait\Laravel\Firebase\ServiceProvider::class to your providers in the config/app.php file
run a vendor publish
Then in your controller you could have something like this
namespace App\Http\Controllers;
class FirebaseController extends Controller {
//
protected $database;
public function __construct()
{
$this->database = app('firebase.database');
}
public function index(){
$new_post = $this->database->getReference('your-reference')>push(["title" =>"something"]);
} }
Remember: on Linux, place Firebase config files etc. in a folder that user 'apache' can read! So, for example, do not place such files in /home/myname/firebase.json. Even if you do chmod 777 firebase.json, this file may not be accessible by user 'apache', hence the 404.
Then you do not need to use env variables.
$factory = (new Factory())->withServiceAccount(DIR.'/vendor/firebase-adminsdk.json');

Laravel policy always returns 403

so I made a policy and whatever I do the Web page returns 403. im very new to laravel so most likely im missing something :)
I made a model by
php artisan make:model exercise | (I know I'm supposed to capitalize models but it was a typo)
Controller:
php artisan make:controller ExercisesController
Policy:
php artisan make:policy ExercisePolicy -m exercise
I registered policy in AuthServiceProvider.php (Also tried as 'App\Models\exercise'=>'App\Policies\ExercisePolicy'):
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
exercise::class => ExercisePolicy::class,
];
In ExercisesController.php this is the function in which I use authentication:
public function create(\App\Models\User $user)
{
$this->authorize('create', $user);
return view('exercises/create');
}
And in policy this is how my create function looks like
public function create(User $user)
{
return $user->admin == true;
}
The route:
Route::get('/exercises/create', [App\Http\Controllers\ExercisesController::class, 'create']);
I tried putting die("Policy is called); and trying to just return true from the policy create function to check if it gets to that but it still returned 403 , at this point I'm pretty sure that the policy itself is not being called as it also returns 403 on default
If anyone could help thanks in advance!
The call to authorize is using the second argument to figure out what Policy to use. Since the second argument is $user it would be looking for a Policy for the User model which you have not defined. To use the Policy for the exercise model you would have to pass the class name so it would know what Policy to use:
$this->authorize('create', exercise::class);
Though you should correct your typo and rename the exercise.php file to Exercise.php and the classname to Exercise.
Laravel 8.x Docs - Authorization - Writing Policies - Methods without Models
Laravel 8.x Docs - Authorization - Authorization Actions using Policies - Via Controller Helpers - Actions That Don't Require Models
I had this same issue and what I learnt was that Policies would work only on authenticated route.
Make sure your request is authenticated while implementing policies.

Laravel Auth::id() return null after login

I have a login form to access to my web page.
In my local computer everything works fine. But now I upload my project to my server and when I login the directive #auth() is null.
I put in my controller this: dd(Auth::id()); and in my local server returns a Id but in the production server returns null...
in web.php I have tis code:
Route::group(['middleware' => 'role:admin' OR 'role:user'], function () {
Route::get('/users/inicio', function(){
dd(Auth::id());
return view('frontend.dashboardUser');});
});
This return null
Can you help me?
Thank you
I think there might be some session problem, It might not be maintaining the session state.
My suggestion:
Try echo session_id() multiple times, If every time different id is generated then there will be some problem with the session on server otherwise not.
Have you registered a new user after you pushed your code to the production? I mean have you logged in using an existing user on production? I believe your production and local Database is different and the user who exists on local does not exist on production DB.
Register a new user and login as the new user and then try accessing the route to see if you get the auth id.
For a security reason, you can't access the login user or any other session into the web.php file as well as a constructor of the class.
To archive this you can use middleware something like this:
public function __construct() {
$this->middleware(function (Request $request, $next) {
if (!\Auth::check()) {
return redirect('/login');
}
$this->userId = \Auth::id(); // you can access user id here
return $next($request);
});
}
This link can help you more. Good luck!!!

How do I convert Laravel 4.2 beforeFilter in controller into custom middleware in Laravel 5.2

I'm in the process of upgrading a Laravel 4.2 app I inherited to Laravel 5.2. The app has multiple roles for logged in users that were handled with a before filter. Each controller has an array of functions and roles allowed for those functions:
public $actionFilter = [
'directories-create'=>['super','tsr'],
'directories-destroy'=>['super','tsr'],
'directories-edit'=>['super','tsr'],
'directories-directoryinfo'=>['super','tsr','admin'],
'directories-index'=>['super','tsr'],
'directories-store'=>['super','tsr'],
'directories-update'=>['super','tsr'],
];
then in the construct function it calls two beforeFilters that were in Controller.php
public function __construct()
{
$this->beforeFilter('#filterAuthorization');
$this->beforeFilter('#rerouteSite');
}
Controller.php had a public function filterAuthorization that checked if user's role had access to the route, and a public function rerouteSite that allowed user to stay on the same page but switch between accounts (for example, for a support rep).
I've spent a fair amount of time reading the manual, Googling and reading various tutorials, but I'm still unclear how to get my route-role array connected to the auth middleware. The Laravel docs provide syntax but not the context and the examples I've read either take a different approach or have a different usecase from mine.
I tried leaving the filter functions in Controller.php and calling them like this in the construct:
public function __construct()
{
$this->middleware('#filterAuthorization');
$this->middleware('#rerouteSite');
}
I get an error message: "Class #filterAuthorization does not exist"
I tried putting those functions in app\Http\Middleware\Authenticate, but I get the same error message: "Class #filterAuthorization does not exist"
I followed the steps on Matt Stauffer's blog here (https://mattstauffer.com/blog/laravel-5.0-middleware-filter-style/) and here (https://mattstauffer.com/blog/passing-parameters-to-middleware-in-laravel-5.1/) and on Nwanze Franklin's post here (https://dev.to/franko4don/deep-dive-into-middlewares-in-laravel-doo) as follows.
Create two new middleware files with Artisan
php artisan make:middleware FilterAuthorization
php artisan make:middleware RerouteSite
Edit the new middleware files with the functions from the old Controller.php
Register the new middleware in App\Http\Kernel
protected $routeMiddleware = [
'filterauth' => \Illuminate\Routing\Middleware\FilterAuthorization::class,
'reroutesite' => \Illuminate\Routing\Middleware\RerouteSite::class,
];
Edit the public function __contstruct() in the Controllers than need filtering
public function __construct()
{
$this->middleware('FilterAuthorization');
$this->middleware('RerouteSite');
}
Run
composer dump-autoload
php artisan clear-compiled
php artisan optimize
and I still get the same error:
Class FilterAuthorization does not exist
I'm sure there's a simple way to put this together without rewriting the whole role authorization system. Can someone point me in the right direction?
The kernel registration needs to reference the correct file locations as follows:
'filterauth' => \App\Http\Middleware\FilterAuthorization::class,
'reroutesite' => \App\Http\Middleware\RerouteSite::class,
And the controller boot should use the aliases rather than the class names:
public function __construct()
{
$this->middleware('filterauth');
$this->middleware('reroutesite');
}
Then Laravel can find the custom middleware.

Laravel 5 - redirect

I'am studying laravel 5 and I have an error with a route redirect.
I have a controller with two functions:
class MainController extends Controller
{
public function index() {
//Some code
return view('index.main',compact('someDatas');
}
public function update(Request $request) {
//Some code here
return redirect(route('main'));
}
}
Here is my route.php
Route::get('/', "main\MainController#index") -> name('main');
Route::get('/update', "main\MainController#update") -> name('update');
In my main.blade.php view, I have a link with a redirect to an update update route:
{{$source -> nom}}
When I click on the link, I get an error:
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
The URL is https://127.0.0.1:8000/update, but when i remove the 's' of HTTPS I'm redirected to the main menu.
I don't understand why this error happens, I have other applications with similar code that work fine.
Thanks for your time and your responses!
This has probably nothing to do with Laravel. When you use HTTPS is tries to use a secure connection. But, you probably do not have a valid certificate for your "localhost" domain. So, you will usually get warnings. I googled your error and found the following: https://support.mozilla.org/nl/questions/1117296 It probably has something to do with your Anti Virus software.
When you use HTTP it will not try to use a secure connection and not verify de site you are connecting to. Which is the reason it works. You should use HTTP for localhost and HTTPS for production.
So again, this has nothing to do with Laravel or your code. It is something to do with HTTPS SSL and certificates. So try using HTTP instead for local development.
Try this way it's working for me.
web.php
Route::match(['get','post'],'/admin/edit_users/{id}','UsersController#EditUser');
user.blade.php
<td><a href="{{ url('/admin/edit_users',$user->id)}}">
<i class="icon icon-edit " style="font-size: 20px;color:green;"></i></a></td>
UsersController.php
public function EditUser(Request $request,$id){
$user=User::where(['id'=>$id])->first();
if($request->isMethod('post')){
$data= array('fname' =>$request->input('fname'),
'lname' =>$request->input('lname'),
'contact' =>$request->input('contact'),
);
$upatedata= DB::table('users')->where('id', $id)->update($data);
if($upatedata){
return redirect('admin/users')->with('flash_message_success','User has been update Successfully');
}else{
return redirect('admin/users')->with('flash_message_error','Incorrect User Data');
}
}
return view('admin.users.edit_user',compact('user'));
}

Resources