How to test cookie which created by service in Laravel - 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()); // ""
}
}

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.

Laravel :: call method in helper class with constructor

as I mentioned in last question I am beginner in Laravel therefore I need some help ,I have to make helper class to create random Id for some tables ,I create this class with table constructor to recieve deffirent tables :
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\DB;
class RandomId
{
public function __construct($my_table)
{
$this->my_table=$my_table;
}
public function get_id()
{
$id = mt_rand(1000000000, 9999999999);
if($this->check_id($id)){
get_id();
}
return $id;
}
public function check_id($id)
{
$table=DB::table($this->my_table)->where('id',$id)->get();
if (count($course)==0){
return false;
}
return true;
}
}
then I add it as alias in config/app.php
'RandomId' => App\Helpers\RandomId::class,
now I want to call it in controller ,I did somethinf like this but don't work :
<?php
namespace App\Http\Controllers\course;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\RandomId;
class Course_controller extends Controller
{
public function add(Request $request)
{
$id=RandomId::get_id('courses');
dd($id);
}
}
I get this error :Non-static method App\Helpers\RandomId::get_id() should not be called statically
It's because get_id function is not static. You should add static keyword when defining static methods:
public static function get_id()
{
....

How to Call Subfolder Controller method in Routes in CodeIgniter 4

I have controllers in subfolders
--Controllers
----Admin
--------UserController
--------AccountController
----User
--------UserController
--------AccountController
I write routes for it
$routes->group('user', function ($routes){
$routes->get('dashboard', 'UserDashboard::index');
$routes->get('changePassword', 'User\AccountController::changePassword');
});
It give me 404 even though I have method and have something output as well
Controller code
<?php namespace App\Controllers;
use App\Controllers\BaseController;
class AccountController extends BaseController
{
public function index()
{
echo "Hello";
exit();
return view('user/account/changePassword');
}
public function changePassword()
{
echo "Change Password View";
exit();
return view('user/account/changePassword');
}
}
You need to change the namespace of your controllers.
User controllers
<?php namespace App\Controllers\User;
use App\Controllers\BaseController;
class AccountController extends BaseController
{
}
Admin controllers
<?php namespace App\Controllers\Admin;
use App\Controllers\BaseController;
class AccountController extends BaseController
{
}

Policy can't acess User in Delete/Patch Route

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');
});

Request class injection in repository class

I have following repository class
<?php
namespace App\Repositories;
use App\Customer;
use App\Comment;
use App\CustomerCode;
use Illuminate\Support\Facades\Request;
class CustomerRepository {
use ValidatesRequests;
public function getAll($search=null,Request $request)
{
if($search){
return Customer::where('name','like',"%$search%")->paginate(5);
}
return Customer::paginate(5);
}
}?>
and controller class
<?php
namespace App\Http\Controllers;
use App\Repositories\CustomerRepository;
use Illuminate\Http\Request;
class CustomerController extends Controller{
private $customerRepo;
function __construct(CustomerRepository $customerRepo){
$this->customerRepo = $customerRepo;
}
function index(Request $request){
return $this->customerRepo->getAll($request->input('search',null));
}
}
this gives me error
Type error: Argument 2 passed to
App\Repositories\CustomerRepository::getAll() must be an instance of
Illuminate\Support\Facades\Request, none given, called in
C:\xampp\htdocs\avmaxapi\app\Http\Controllers\CustomerController.php
on line 21
i know i havenot passed 2nd argument but should not it inject automatically
and i donot want to pass request object everytime from controller;
use use Illuminate\Http\Request;
and not: use Illuminate\Support\Facades\Request;
at the following:
<?php
namespace App\Repositories;
use App\Customer;
use App\Comment;
use App\CustomerCode;
use Illuminate\Http\Request;
class CustomerRepository {
use ValidatesRequests;
public function getAll($search=null,Request $request)
{
if($search){
return Customer::where('name','like',"%$search%")->paginate(5);
}
return Customer::paginate(5);
}
}?>

Resources