Laravel: Inject Auth into a Service - laravel

How do I inject Auth into a service? I know in the service itself, I do:
public function __construct(Illuminate\Auth\AuthManager $Auth)
{
$this->authService = $Auth;
}
But how do I pass it in the service provider? I.e.
$this->app->bind('SomeService', function() {
return new SomeService(??); // What goes here?
});

I believe you should allow the laravel app to build an object based on your dependency here. I haven't tried this myself but looks like this might work:
return new SomeService(App::make(Illuminate\Auth\AuthManager));

Related

How to call Service class function?

use App\Http\Controllers\ATransaction;
use App\Service\ATransactionServices;
class TransactionController extends Controller {
public function ATransaction(Request $request, ATransactionServices $ATransaction){
try {
$validated_request = $this->validateRequest($request);
} catch (ValidationException $exception) {
return redirect()->back()->withInput()->withErrors($exception->errors());
}
How to call my service class function to replace into
$validated_request = $this->validateRequest($request);
Can someone show me the right way?
You can traits concepts or can directly use DI ( dependency Injection ) to implement service into this class.
For traits, you can check How to create traits in Laravel
And if you want to use Dependency Injection then do something like:
public function __construct(ATransactionServices $aTransactionServices)
{
$this->aTransactionServices = $aTransactionServices;
}
Then inside the method you can directly use the service methods:
$this->aTransactionServices->methodName();
If you want to use method inside the try and catch than simplest way is to add them in controller.
class TransactionController extends Controller {
//This will help in directly injecting the service into the container
public function __construct(ATransactionServices $aTransactionServices)
{
$this->aTransactionServices = $aTransactionServices;
}
//Otherwise you can create a custom request to handle validations on the request level
public function ATransaction(Request $request){
try {
$validated_request = $this->aTransactionServices->validateRequest($request);
//Here you can setup the validation mechanism like custom status based validation e.g. $validated_request['status'] which can be true or false otherwise use validator instance to use $validated_request->fails() to check
if($validated_request->fails()) {
//Here pass the data and you can handle on catch how you want to send response
throw new Exception('Exception details or validator instance');
}
} catch (Exception $exception) {
return redirect()->back()->withInput()->withErrors($exception->errors());
}
}
But if your only purpose is to handle the validations than you can use custom request in laravel for validations handling: Custom Request
Hope this works for you and resolves your issue.
have a great day.
$validated_request = $ATransaction->validateRequest($request);

Laravel 8 Fortify Redirect based on roles without jetstream

I am looking for a good tutorial or advice on how to redirect after authenticated based on roles in laravel 8 fortify without jetstream. I have found one that says to create a new LoginResonse.php in App\Http\Responses\loginresponse.php which I did but I am not sure where to register this new response because the tutorial I am using says to do it in Jetstreamserviceprovider but I am not using Jetstream. Any ideas?
You will want to register your custom LoginResponse in the FortifyServiceProvider, specifically the boot method.
public function boot()
{
$this->app->singleton(
\Laravel\Fortify\Contracts\LoginResponse::class,
\App\Http\Responses\LoginResponse::class
);
}
This registers your custom LoginResponse with Laravels IoC service container and informs Laravel to provide your LoginResponse to methods that require an instance of an object which implements the LoginResponse from Fortify.
Inside your custom LoginResponse and in the toResponse method, you can perform whatever logic you require. For example;
public function toResponse($request)
{
if ($request->wantsJson()) {
return response()->json(['two_factor' => false]);
}
if (Auth::user()->hasRole('admin') {
return redirect(route('admin.index'));
}
}

Mocking a service class inside controller

I am trying to write a Feature test for my controller. To simplify my current situation, imagine my controller looks like this:
public function store(Business $business)
{
try {
(new CreateApplicationAction())->execute($business);
} catch (Exception $e) {
return response()->json(['message' => 'error'], 500);
}
return response()->json(['message' => 'success']);
}
What I am trying to achieve is, instead of testing CreateApplication class logic inside my integration test, I want to write another unit test for it specifically.
Is there a way I can simply say CreateApplicationAction expects execute() and bypass testing inside it? (without executing the code inside execute())
/** #test */
public function can_create_application()
{
$business = Business:factory()->create();
$mock = $this->mock(CreateApplicationAction::class, function (MockInterface $mock) use ($business) {
$mock->shouldReceive('execute')
->once()
->with($business)
->andReturn(true);
});
$response = $this->post('/businesses/3/application', $data);
$response->assertOk();
}
I saw online that people create "MockCreateApplicationAction" class but if possible I don't want to create another class as I don't want any logic to be inside it at all.
Is it possible?
class CreateApplicationAction
{
public function execute($business) {
dd("A");
// Business Logic...
}
}
So when I do the Mock, dd() should never be called. Or I am going in the wrong direction?
You will need to use Laravels container to resolve your class. The basic approach is to use the resolve() method helper. PHP does not have dependency injection, so you need to use one to make it possible, in Laravel the container solves that.
resolve(CreateApplicationAction::class)->execute($business);
On constructors, controller methods, jobs, events, listeners and commands (rule of thumb if the method is named handle), you can inject classes into the parameters and they will resolve through the container.
public function store(Business $business, CreateApplicationAction $applicationAction)
{
try {
$applicationAction->execute($business);

Laravel unit testing automatic dependency injection not working?

With Laravel Framework 5.8.36 I'm trying to run a test that calls a controller where the __construct method uses DI, like this:
class SomeController extends Controller {
public function __construct(XYZRepository $xyz_repository)
{
$this->xyz_repository = $xyz_repository;
}
public function doThisOtherThing(Request $request, $id)
{
try {
return response()->json($this->xyz_repository->doTheRepoThing($id), 200);
} catch (Exception $exception) {
return response($exception->getMessage(), 500);
}
}
}
This works fine if I run the code through the browser or call it like an api call in postman, but when I call the doThisOtherThing method from my test I get the following error:
ArgumentCountError: Too few arguments to function App\Http\Controllers\SomeController::__construct(), 0 passed in /var/www/tests/Unit/Controllers/SomeControllerTest.php on line 28 and exactly 1 expected
This is telling me that DI isn't working for some reason when I run tests. Any ideas? Here's my test:
public function testXYZShouldDoTheThing()
{
$some_controller = new SomeController();
$some_controller->doThisOtherThing(...args...);
...asserts...
}
I've tried things like using the bind and make methods on app in the setUp method but no success:
public function setUp(): void
{
parent::setUp();
$this->app->make('App\Repositories\XYZRepository');
}
That's correct. The whole idea of a unit test is that you mock the dependant services so you can control their in/output consistently.
You can create a mock version of your XYZRepository and inject it into your controller.
$xyzRepositoryMock = $this->createMock(XYZRepository::class);
$some_controller = new SomeController($xyzRepositoryMock);
$some_controller->doThisOtherThing(...args...);
This is not how Laravels service container works, when using the new keyword it never gets resolved through the container so Laravel cannot inject the required classes, you would have to pass them yourself in order to make it work like this.
What you can do is let the controller be resolved through the service container:
public function testXYZShouldDoTheThing()
{
$controller = $this->app->make(SomeController::class);
// Or use the global resolve helper
$controller = resolve(SomeController::class);
$some_controller->doThisOtherThing(...args...);
...asserts...
}
From the docs :
You may use the make method to resolve a class instance out of the
container. The make method accepts the name of the class or interface
you wish to resolve:
$api = $this->app->make('HelpSpot\API');
If you are in a location of your code that does not have access to the
$app variable, you may use the global resolve helper:
$api = resolve('HelpSpot\API');
PS:
I am not really a fan of testing controllers like you are trying to do here, I would rather create a feature test and test the route and verify everything works as expected.
Feature tests may test a larger portion of your code, including how
several objects interact with each other or even a full HTTP request
to a JSON endpoint.
something like this:
use Illuminate\Http\Response;
public function testXYZShouldDoTheThing()
{
$this->get('your/route')
->assertStatus(Response::HTTP_OK);
// assert response content is correct (assertJson etc.)
}

How to swap out dependency in laravel container

I have registered a Paypal service provider:
App\Providers\PaypalHelperServiceProvider::class,
and, when I type hint it in my controller it properly resolves:
public function refund(Request $request, PaypalHelper $paypal) {...
Here is my provider class:
class PaypalHelperServiceProvider extends ServiceProvider
{
protected $defer = true;
public function register()
{
$this->app->bind('App\Helpers\PaypalHelper', function() {
$test = 'test';
return new PaypalHelper();
});
}
public function provides()
{
$test = 'test';
return [App\Helpers\PaypalHelper::class];
}
}
Everything works as expected. Now I wanted to be able to modify controller to take a PayPal interface. I would then update my service provider to conditionally pass in either the real class or a mock one for testing, using the APP_ENV variable to determine which one to use. I put some debuggers into the service provider class and could not get it to ever go in. I thought perhaps that it only loads them on need, so I put a breakpoint inside my controller. The class did resolve, but it still never went into the service provider class! Can someone explain to me why this is the case? Even when I modified the code to pass in a different class type it did not pick up.
EDIT:
Here is the code flow I see when I debug this:
ControllerDispatcher -> resolveClassMethodDependencies -> resolveMethodDependencies -> transformDependency. At this point we have the following laravel code in the RouteDependencyResolveerTrait:
protected function transformDependency(ReflectionParameter $parameter, $parameters, $originalParameters)
{
$class = $parameter->getClass();
// If the parameter has a type-hinted class, we will check to see if it is already in
// the list of parameters. If it is we will just skip it as it is probably a model
// binding and we do not want to mess with those; otherwise, we resolve it here.
if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {
return $this->container->make($class->name);
}
}
Since getClass() always resolves to the interface name, when we call container->make(), it always fails with
Target [App\Helpers\PaypalHelperInterface] is not instantiable.
Change
$this->app->bind('App\Helpers\PaypalHelper', function() {
$test = 'test';
return new PaypalHelper();
});
To
if (app()->environment('testing')) {
$this->app->bind(
PaypalHelperInterface::class,
FakePaypalHelper::class
)
} else {
$this->app->bind(
PaypalHelperInterface::class,
PaypalHelper::class
);
}
I finally found out the issue. My problem was that my provider wasn't being picked up at all. Here was the solution
composer dumpautoload
php artisan cache:clear
https://laravel.io/forum/02-08-2015-laravel-5-service-provider-not-working

Resources