Laravel, Guzzle - Check if Cookie is set - php

I wish to check if the cookie is set, when doing the bottom getUsername(). Can anyone help me with a quick fix for this? I've tried for hours without luck.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cookie;
class CookieController extends Controller
{
public function setCookie(\stdClass $request)
{
$minutes = 60;
$response = new Response(view('panel.panel'));
$response->withCookie(cookie('userInfo', $request, $minutes));
return $response;
}
public function getCookie(){
$val = cookie::get('userInfo');
return $val;
}
public function getUsername(){
$cookie = cookie::get('userInfo');
return $cookie->message->username;
}
public function getShopID(){
$cookie = cookie::get('ShopID');
return $cookie->message->shopID;
}
}
?>

You could use isset or compare with null
public function getUsername(){
$cookie = cookie::get('userInfo');
if ($cookie !== null) {
// do something like set cookie
// return username
}
}

Try using the method hasCookie():
public function getUsername(Request $request)
{
if ($request->hasCookie('userInfo')) {
$cookie = $request->cookie('userInfo');
return $cookie->message->username;
}
}

Related

how to pass parameter to the route php

Heres the code for the route:
<?php
use app\controllers\Home;
use app\core\App;
$app = new App();
$app->router->get('/', function(){
echo "hello there";
});
$app->router->get('user/', 'user');
$app->router->get('/contact', [Home::class,'contacts']);
$app->router->post('/contact', function(){
echo "handlecontact";
});
$app->run();
Heres the code for the router core class:
<?php
namespace app\core;
class router{
public Request $request;
public Response $response;
protected array $routes = [];
public function __construct(Request $request,Response $response)
{
$this->request = $request;
$this->response = $response;
}
public function get($path, $callback){
$this->routes['get'][$path] = $callback;
}
public function post($path, $callback){
$this->routes['post'][$path] = $callback;
}
public function resolve(){
$path = $this->request->getpath();
$method = $this->request->getmethod();
$callback = $this->routes[$method][$path] ?? false;
if($callback == false){
$this->response->setstatuscode(404);
return "not found";
}
if(is_array($callback)){
$callback[0] = new $callback[0]();
}
return call_user_func($callback,$this->request);
}
I want to be able to declare a route and pass a parameter to it. If i do it so like that it tells me route not found.
Like i want to be able to write the route like this:
$app->router->get('/contact/{id}', function(){
echo $id; // to echo it out like this from the controller
});
Can someone be of good help or also add something to the idea. Thanks in advance

Connecting method/function in laravel

I'm trying to create a class function which resembles how we used to fetch database listing and convert into a dropdown listing.
eg: DB::table()->where()->get()
what i would like to achieve in laravel custom class or through model is this
Dropdown::fetch()->toArray()
Dropdown::fetch()->toDropdown()
I tried to figure out how this can be done through google. But couldn't find any solution to it.
I'm using laravel 5.8
--
Edit - Sample Code added
Code tried:
namespace App\Http\Models;
use DB;
use Closure;
use BadMethodCallException;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Database\Eloquent\Model;
class Dropdown extends Model
{
private $result = [];
private $default;
public function _cities(){
$tbl_cities = config("tables.TBL_meta_cities");
$result = DB::table($tbl_cities)->select('id', 'cityname')
->orderBy('id')->get()->toArray();
$this->result = $result;
}
public function _select(){
}
public function _list(){
return $this->result;
}
public function _setDefault($def=''){
}
public static function __callStatic($method, $parameters)
{
$action = '_'.$method;
if(method_exists(get_called_class(), $action))
self::$action(...$parameters);
else echo 'not found';
}
public function __call($method, $parameters)
{
$action = '_'.$method;
if(method_exists($get_called_class(), $action))
self::$action(...$parameters);
else echo 'not found';
}
}
and i tried
Dropdown::cities()->list()
but ended with bugs
Well i figured it out myself.
class Dropdown extends Model
{
private static $result = [];
private function getCities(){
$result = City::select('id', 'cityname')
->orderBy('id')->get()->toArray();
self::$result = $result;
}
public function toArray(){
return self::$result;
}
public function toDropdown(){
// Do the dropdown works
}
/**
* Dynamically handle calls to the class.
*
* #param string $method
* #param array $parameters
* #return mixed
*
* #throws \BadMethodCallException
*/
public function __callMethod($method, $parameters){
// Check with inclusive
$class = get_called_class();
$avail = false;
$action = '';
// Check method availability - direct
if(!$avail){
$action = $method;
$avail = method_exists($class, $action);
}
// Check method 2
if(!$avail){
$action = 'get'.ucwords($method);
$avail = method_exists($class, $action);
}
if($avail){
// Call the method
$return = self::$action(...$parameters);
if(!empty($return)) return $return;
} else {
// Throw error if method not found
throw new BadMethodCallException("No such method exists: $name");
}
return new self;
}
public static function __callStatic($method, $parameters){
return (new self)->__callMethod($method, $parameters);
}
public function __call($method, $parameters){
return (new self)->__callMethod($method, $parameters);
}
}
All i need to do is return new self which does the trick instead of return $this so that the trailing function can be called easily.
Now i can able to call that function like this
Dropdown::cities()->toArray();
Reference:
https://stackoverflow.com/a/41631711/1156493
Thank you #Joseph for your time & support.

SLIM FRAMEWORK 3: Can't pass variable from middleware to controller

What's wrong with my code? I can't pass variable from my Auth middleware to controller. In controller, the attribute "null".
Index:
$c = new \Slim\Container($configuration);
$api = new \Slim\App($c);
$api->group('/', function () use ($api) {
$this->post('login', '\AuthController:login');
...
$this->post('getIngredientsCategories', '\IngredientsController:getIngredientsCategories');
})->add(new ApiAuthenticateController());
$api->run();
Middleware (ApiAuthenticateController)
use \Firebase\JWT\JWT;
class ApiAuthenticateController
{
public function __invoke($request, $response, $next)
{
$jwtDecoded = null;
$req = $request->getUri()->getPath();
$_req = RequestValidatorController::isRequestEnabled($req);
if ($_req !== false) {
if ($_req['login_required']) {
$jwt = filter_var($request->getHeaderLine('AUTHORIZATION'), FILTER_SANITIZE_STRING);
$jwt = explode(" ", $jwt)[1];
try {
$jwtDecoded = JWT::decode($jwt, JWT_SECRET, array('HS256'));
} catch (\Exception $e) {
return $this->deny_access($response);
}
}
$request = $request->withAttribute('foo', $jwtDecoded);
//HERE - attribute "foo" in $request exists - checked by var_dump()..
$response = $next($request, $response);
$response = $response->withHeader('Content-type', 'application/json');
return $response;
} else {
return $this->deny_access($response);
}
}
IngredientsController
class IngredientsController extends Controller
{
private $_ingredients;
public function __construct(\Interop\Container\ContainerInterface $container)
{
parent::__construct($container);
}
}
Controller
class Controller
{
private $request;
private $response;
protected $data;
protected $method;
protected $user;
public function __construct(Interop\Container\ContainerInterface $container)
{
$this->request = $container->get('request');
$this->response = $container->get('response');
$this->data = (object)Tools::stripInput($this->request->getParsedBody());
$this->method = $this->request->getUri()->getPath();
$this->user = $this->request->getAttribute('foo');
var_dump($this->user);
// returns NULL. if $this->request->getAttributes()... returns empty
}
}
Please note, that code is "cleaned" for this post and for better readability, some functions and conditions where deleted. Code is working - sorry for possible typos.
the problem is coming from here
in the middleware ApiAuthenticateController, you should change the code like this
$request = $request->withAttribute('foo', $jwtDecoded);
// you should return the $next here not to do anything else
return $next($request, $response);
and in your IngredientsController:getIngredientsCategories part of code you should return the
function getIngredientsCategories ($request, $response, $args){
//do your job...
$response = $response->withHeader('Content-type', 'application/json');
return $response;
}
and finally, in the constructor, you have don't have the actual $request after the middleware I think so you would have the $this->request->getAttributes() inside your getIngredientsCategories function
Hope it helps.

Authentication Middleware Slim 3.0

I am using a middleware to redirect to login page if session is not set.
$app->get('/dashboard', function (Request $request, Response $response, $args) {
include_once('employee-portal/dashboard.php');
return $response;})->add(new AuthMiddleware('counter', true, $app->getContainer()));
and my middleware:
class AuthMiddleware implements MiddlewareInterface{
private $min_role = 'counter';
private $redirect = true;
private $container = null;
public function __construct($role_required, $login_redirect, $container)
{
$this->min_role = $role_required;
$this->redirect = $login_redirect;
$this->container = $container;
}
public function __invoke($request, $response, $next)
{
if ($this->userIsAuthorised()) {
return $next($request, $response);
} else {
if ($this->redirect) {
/**
* #var \Slim\Router router`
*/
return $response->withRedirect(Details::getBaseUrl() . '/login' . '?ref=' . $request->getUri());
}
return $response->withStatus(401)->write("Sorry boss you are not authorised to see my secret");
}
}
private function userIsAuthorised()
{
if ($this->min_role == 'counter') {
return true;
} else if (SessionManager::isLoggedIn()) {
if ($_SESSION['user_type']=='counter') {
return true;
}
}
return false;
} }
but this doesn't works.
i can even see the dashboard page without login. and even after login i cannot access the $_SESSION['user_type'] session variable.
any help would be appriciated. thanks in advance.
You are passing 'counter' into your AuthMiddleware constructor, causing it to always return true in the first if() statement of userIsAuthorised() method.
if ($this->min_role == 'counter')
will always be true because you set $this->min = 'counter' in your constructor. Try rewriting the new AuthMiddleware() and constructor so that you just pass in the container. Before calling the new AuthMiddleware() you can do the following:
$container['min_role'] = 'counter' if you need it elsewhere in your app.

How to access data of one function to another in laravel

Okay the issue is something like this
I have a function in AController
public function index()
{
$store = Store::(query)(to)(rows)->first();
return view('store.index', compact('store'));
}
Now in the same controller I have another function
public function abc()
{
return view('store.abc');
}
Now to this function I also want to send the compact('store') to the view abc I can just add the query again in the abc() function but that would be lazy and make performance issues. Is there a way that I can access $store object in other functions too?
If I understand you correctly you want to access the same query from two places. So extract getting stores to another method like
private function store()
{
$minutes = 10; // set here
return Cache::remember('users', $minutes, function () {
return Store::(query)(to)(rows)->first();
});
}
Additionally I have cached the query. So it get executed once at a defiened time.
Then access it from other two methods like,
public function index()
{
$store = $this->store();
return view('store.index', compact('store'));
}
public function abc()
{
$store = $this->store();
return view('store.abc', compact('store'));
}
class StoreController extends Controller
{
public function index()
{
return view('admin.store',['data' => $this->getSetting()]);
}
public function getStoreData()
{
//get your data here, for example
$data = Store::where('status',1)->first();
//get all data
//$data = Store::all();
return ($data);
}
}
Try the following. Not testing but it should work for you.
class AController
{
public function getStore()
{
$store = Store::(query)(to)(rows)->first();
return compact('store');
}
public function index()
{
return view('store.index', $this->getStore());
}
public function abc()
{
return view('store.abc', $this->getStore());
}
}

Categories