Accessing Model in utility in laravel - laravel-5

I'm trying to access the User model in a utility I built that will eventually send emails out, this is being triggered with by cron, and I'm using php artisan schedule:run to test it. Below is the utility I'm starting to build out, and currently when test it I am getting 'I was triggered'. This is being triggered by a registered console command. Thats all working.
<?php
namespace App\Utility;
use Log;
use Mail;
use App\User;
class ReferralProgramUtility
{
static public function test()
{
LOG::info("I was triggered");
}
}
However, when I change this to pull in the User model....
<?php
namespace App\Utility;
use Log;
use Mail;
use App\User;
class ReferralProgramUtility
{
static public function test()
{
$user = User::all();
LOG::info($user);
}
}
I get the following error....
Trying to get property of non-object in /var/www/html/appname/app/User.php:32
I'm using another utility that has a similar configuration and uses the User model and this work fine, the only difference is that this is on is being triggered by task scheduler. Not sure what is causing this, and I'm fairly new to Laravel so any tips or recommendation would be hugely appreciated. Thanks, in advance.

Related

Laravel 5.6 testing Notification::assertSentTo() not found

Struggling since multiple days to get Notification::assertSentTo() method working in my feature test of reset password emails in a Laravel 5.6 app, yet receiving ongoing failures with following code:
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserPasswordResetTest extends TestCase
{
public function test_submit_password_reset_request()
{
$user = factory("App\User")->create();
$this->followingRedirects()
->from(route('password.request'))
->post(route('password.email'), [ "email" => $user->email ]);
Notification::assertSentTo($user, ResetPassword::class);
}
}
I have tried several ideas including to use Illuminate\Support\Testing\Fakes\NotificationFake directly in the use list.
In any attempt the tests keep failing with
Error: Call to undefined method Illuminate\Notifications\Channels\MailChannel::assertSentTo()
Looking forward to any hints helping towards a succesful test.
Regards & take care!
It seems like you are missing a Notification::fake(); For the correct fake notification driver to be used.
Notification::fake();
$this->followingRedirects()
...

Laravel Dependency Injection issue with Controller?

I setup the dependency injection as I felt it should go into my Patient Controller but for some reason it will never execute the dependency on the index function on the last line, it will even return the $request data before it but for some reason will not execute the data in the Patient Repository I attempt to return.
I have attempted to just do:
return (new Patient)->getByAccNumAndDateOrZip($this->client_code, $this->account_number, $this->dob, $this->zip);
Also, keep in mind yes all $requests do have a valid value and do not return a empty or null value.
And still get nothing back....
namespace App\Http\Controllers\api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//Repositories
use App\Repositories\Patient;
class PatientController extends Controller {
private $patient;
public function __construct(Patient $patient) {
$this->middleware('auth.client');
$this->patient = $patient;
}
public function index(Request $request) {
//I can do return $request->client_code
//But I can't use this dependency... It's weird...
return $this->patient->getByAccNumAndDateOrZip($request->client_code, $request->account_number, $request->dob, $request->zip);
}
}
I'm expecting to call to my dependency that pulls all the my patients by account number. The dependency is just a standard class with a namespace of App\Repositories it has no set constructor just a couple standard public functions that will take specific variables in the function.
After reviewing the log files in laravel I was able to see that the system was stating that the class name has already been used so I would have to choose something else.
This was suggested by Matt Wohler to check the logs and boy did it help me!
Thanks Again for all the help!

Cannot get Laravel Mail::to()->later() to work

I'm trying to send a time-delayed email via a Redis queue and Mailgun using the following code...
$when = \Carbon\Carbon::now()->addMinutes(5);
Mail::to($demoDownloader->Email)->later($when, new DemoRequestFollowUp($demoDownloader));
I can see that the job is added to the redis queue (using Redis Desktop Manager) and stays in the queue for 5 minutes before disappearing from the queue. Unfortunately, it never appears in the Mailgun logs.
If I instead use this line of code...
Mail::to($demoDownloader->Email)->send(new DemoRequestFollowUp($demoDownloader));
...then the email appears in the Mailgun logs and subsequently arrives in the destination mailbox successfully (minus the time delay of course).
No error messages are written to storage/logs/laravel.log so I'm at a bit of a loss as to why this isn't working. I'm pretty sure I've used the syntax specified in the manual.
By the way, my mailable looks like this...
<?php
namespace App\Mail;
use \App\DemoDownloader;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class DemoRequestFollowUp extends Mailable
{
use Queueable, SerializesModels;
public $requestee;
public function __construct(DemoDownloader $requestee)
{
$this->requestee = $requestee;
}
public function build()
{
return $this->subject('Overview')
->view('email-demo-request-follow-up');
}
}
I'd be most grateful for any input.
I'd neglected to look in the failed_jobs table which gave me the clue I needed...
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\DemoDownloader]
As the DemoDownloader instance being passed into the DemoRequestFollowUp constructor wasn't actually being used, I removed the argument and also removed the $requestee public property from the class and its assignment in the constructor. After making these changes emails were reliably arriving after the specified delay interval had passed.

Creating a helper system in laravel is correct or not?

My helper root
app\http\myHelpers\customClass.php
customClass.php
<?php
namespace App\Http\myHelper;
class CustomClass {
public static function customFunction(){
return 'Custom class working......';
}
}
Controller function
public function test(){
CustomClass::customFunction();
}
routes
Route::get('/test', 'HomeController#test');
There is no need composer command. It is work properly but I am not sure to is it correct system or wrong system. Please help me.
How you organize your code is honestly a personal choice. So there is nothing wrong with your code. You don’t need any composer command because in Laravel everything in the app folder is auto loaded by composer: The App Directory
This is perfectly fine, what you can do additionally is to organize function inside traits and place them e.g. in the /app folder.
<?php
namespace App;
trait HasRoles
{
public function hasPermission(Permission $permission)
{
return $this->hasRole($permission->roles);
}
}
and use this trait inside your controller like
use Authenticatable, Authorizable, CanResetPassword, HasRoles;
just another way of bundling helper functions!

Setup VisualPHPUnit with Laravel

I'm using VisualPHPUnit as a GUI for my unit tests and I want to add it to my Laravel project.
I read this guide but it's obsolete being from 2015. There's no bootstrap.php file in config directory and there are no test_directories and bootstraps variables (I ran grep -rn . -e test_directories is Laravel directory).
Any idea what I can do to be able to add tests with artisan so they are working in VPU? Because Laravel test needs to extend Illuminate\Foundation\Testing\TestCase and VPU test needs to extend \PHPUnit_Framework_TestCase and I can't get it running. Either I don't see the test in VPU when I use Laravel's extend or I can't use Laravel's functions like visit when I use VPU's extend.
Edit:
Here's my PermissionTest.php:
<?php
namespace Visualphpunit\Test;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PermissionTest extends \PHPUnit_Framework_TestCase
{
protected $baseUrl = 'http://localhost/laravel/public';
public function testExample()
{
$this->visit('/')->see('Logowanie');
}
public function createApplication()
{
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
}
...for which I get this error: Fatal error: Class 'Visualphpunit\Test\Illuminate\Foundation\Testing\TestCase not found in .../laravel/VisualPHPUnit-master/tests/PermissionTest.php on line 10

Resources