Policy can't acess User in Delete/Patch Route - laravel

When i call my Api Route with the GET Http-Verb it will return me my user. If i call it with the DELETE or PATCH Route it returns null.
I add the Policy to the complete Controller:
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Shoppingcart;
use Validator;
use Response;
class ShoppingcartController extends Controller
{
public function __construct()
{
$this->authorizeResource(Shoppingcart::class, 'shoppingcart');
}
...
public function destroy()
{
...
}
}
Then i 'die and dump' the user in the Policy:
namespace App\Policies;
use App\User;
use App\Shoppingcart;
use Illuminate\Auth\Access\HandlesAuthorization;
class ShoppingcartPolicy
{
use HandlesAuthorization;
public function before(?User $user, $ability)
{
dd($user);
}
public function update(User $user, Shoppingcart $shoppingcart)
{
}
public function delete(User $user, Shoppingcart $shoppingcart)
{
}
}
I authenticate my Request in the Header and i registerd the Policy in the AuthServiceProvider.php

The Authentication for Web and API is different. The cookies that are set in the frontend, is not considered at the API.
I needed to register the Auth Middleware also to the API Routes:
Route::middleware('auth:api')->group(function(){
Route::apiResource('/shoppingcarts', 'API\ShoppingcartController');
});

Related

How to access inputted token value - Laravel API

I am inputting a token as above and trying to print the token value with the below code. But getting error Undefined variable: token. I'm not sure whether i can access the token as below. Pls help me with ur suggestions.
<?php
namespace App\Http\Controllers;
use App\Models\Files;
use Illuminate\Support\Facades\Auth;
class FileController extends Controller
{
public function upload()
{
$tock=Auth::user()->$token;
dd($tock);
}
}
You are trying to access the $token variable on the user, even though it does not exist.
Instead you should by trying to access the request and the values that are send with the request. This can be achieved using the request() helper or by injecting the Request class into the function.
With injection:
<?php
namespace App\Http\Controllers;
use App\Models\Files;
use Illuminate\Http\Request; // Add request to namespace
use Illuminate\Support\Facades\Auth;
class FileController extends Controller
{
public function upload(Request $request)
{
dd($request->bearerToken());
}
}
Or, without injection:
<?php
namespace App\Http\Controllers;
use App\Models\Files;
use Illuminate\Support\Facades\Auth;
class FileController extends Controller
{
public function upload()
{
dd($request->bearerToken());
}
}
With the bearerToken() method you can access the Bearer token provided in the request.

How to test cookie which created by service in Laravel

route
Route::get('/token', [\App\Http\Controllers\TokenController::class, 'index']);
TokenController.php
namespace App\Http\Controllers;
use App\Services\Token;
class TokenController extends Controller
{
public function index()
{
$tokenService = app(Token::class);
return $tokenService->handle('https://www.nba.com');
}
}
Token Service
namespace App\Services;
class Token
{
public function handle(string $redirect)
{
return redirect($redirect)->withCookie(cookie('token', 'abcd'));
}
}
I want to leave a token in cookies when the user enters the page and redirect to another URL, I am sure the cookie was saved when I check on the browser, but I don't know to do the test that token service did save the cookie in the unit test.
first try
namespace Tests\Unit;
use App\Services\Token;
use Illuminate\Support\Facades\Cookie;
use Tests\TestCase;
class TokenTest extends TestCase
{
public function testToken()
{
app(Token::class)->handle('https://www.nba.com');
dd(Cookie::get('token')); // null
}
}
second try
namespace Tests\Unit;
use App\Services\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class TokenTest extends TestCase
{
public function testToken()
{
app(Token::class)->handle('https://www.nba.com');
Route::get('view-cookie', function (Request $request) {
return $request->cookie('token');
});
$response = $this->get('/view-cookie');
dd($response->getContent()); // ""
}
}

Setup Third party package into custom service provider

I'm trying to apply a sort of "repository-pattern" to a custom service.
What I'd like to do is to actually bind this library to my custom service provider to create an abstraction layer and, eventually, switch that library with another one in the future.
I'm trying to move the 'providers' and 'aliases' references from config/app.php to my service provider, but I get a Class 'GoogleMaps' not found error.
I've added App\Providers\GeoServiceProvider::class to config/app.php providers array and this is my relevant code:
GeoServiceProvider.php(my custom service provider)
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class GeoServiceProvider extends ServiceProvider
{
/** * Register services.
*
* #return void
*/
public function register()
{
$this->app->bind(\App\Interfaces\GeoInterface::class, \App\Services\GoogleGeoService::class);
$this->app->alias(\GoogleMaps\Facade\GoogleMapsFacade::class, 'GoogleMaps');
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
}
}
GeoInterface.phpinterface defining standard methods
<?php
namespace App\Interfaces;
interface GeoInterface
{
public function geoCode();
}
GoogleGeoService.php(The actual library implementation)
<?php
namespace App\Services;
use App\Interfaces\GeoInterface;
class GoogleGeoService implements GeoInterface
{
public function geoCode()
{
$response = \GoogleMaps::load( 'geocoding' ) <--- HERE IS WHERE I GET THE ERROR
->setParamByKey( 'latlng', "45.41760620,11.90208370")
->setEndpoint( 'json' )
->get();
$response = json_decode($response, true);
return $response;
}
}
TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Interfaces\GeoInterface;
class TestController extends Controller
{
protected $geoService;
public function __construct(GeoInterface $geoService) {
$this->geoService = $geoService;
}
public function index() {
return $this->geoService->geoCode();
}
}
Thank you,
Alex

Laravel: Class declaration Compatible error

I am using laravel 5.6, when create controller and when run controller through route, I am facing error like
Declaration of App\Http\Controllers\XyzController::xyz(Illuminate\Http\Request $request) should be compatible with App\Http\Controllers\Controller::xyz($job)
My Code is
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class XyzController extends Controller
{
public function xyz(Request $request)
{
return view('xyz.xyz');
}
}
Missing route parameter: $job
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class XyzController extends Controller
{
public function xyz(Request $request, $job)
{
return view('xyz.xyz');
}
}
The base Controller that XyzController extends from defines a method named xyz with a different signature than the one you are defining.
You will need to adjust the method in XyzController to match the signature of xyz in the base Controller or adjust the base Controller to have a different signature.
Example of the problem:
class A
{
public function xyz($obj) {}
}
class B extends A
{
public function xyz(Illuminate\Http\Request $request) {}
}
Declaration of B::xyz(Illuminate/Http/Request $request) should be compatible with A::xyz($obj)
You forgot to use controller?
use App\Http\Controllers\Controller as Controller

Laravel 5.3 Custom Class

Create a custom class in laravel when I am call in controller construct then
Auth::user() not return any data
When call from in a function then it's work
Class Code
<?php namespace App\Libraries;
use App\User;
use Auth;
use Illuminate\Support\Facades\DB;
use App\Friends;
class AppLibrarie
{
private static $friends_ids = array();
public function __construct()
{
self::$friends_ids=Auth::user();
}
public function getfriends(){
return self::$friends_ids;
}
}
And Controller
<?php
namespace App\Http\Controllers;
use App\Libraries\AppLibrarie;
use Illuminate\Http\Request;
use App\Http\Requests;
class LiveController extends Controller
{
protected $lib;
public function __construct(AppLibrarie $appLibrarie)
{
$this->lib = $appLibrarie;
}
public function search(Request $request){
return response()->json($this->lib->searchdata($request->get('query')));
}
}
Accessing authenticated user sessions has been deprecated in Laravel 5.3. Here is the paragraph in the upgrade guide
In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:
You will need to rethink your Authentication structure a bit if you are to upgrade

Resources