how can i Cache object and its relations in laravel 6 - api

In RatingController:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\RatingResource;
use App\Models\Rating\Rating;
class RatingController extends Controller
{
public function getRatingsByCategory($id)
{
$ratings = cache()->rememberForever('test', function () use ($id) {
return new RatingResource(Rating::findOrFail($id));
});
return response()->json([
'data' => $ratings
]);
}
}
in RatingResource class
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;
class RatingResource extends JsonResource
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->rating_id,
'is_active' => $this->is_active,
'created_at' => '2020',
];
}
}
when i send request to this controller, i get this result
{
"data": {
"id": 3,
"is_active": 1,
"created_at": "2020"
}
}
but when i change each of column in RatingResource like created_at, the result changes.
indeed laravel does not cache final result, it cache the object of my request and when i return that object,it start to convert my object to resource format.
how can i cache the result of ApiResource till i delete this cache key.

You could cache the whole response, this way you would have to add the id to the cache key though, in order to differentiate between the different rating ids.
Something like this:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\RatingResource;
use App\Models\Rating\Rating;
use Illuminate\Support\Facades\Cache;
class RatingController extends Controller
{
public function getRatingsByCategory($id)
{
return Cache::rememberForever("test:{$id}", function () use ($id) {
return RatingResource(Rating::findOrFail($id));
});
}
}

Related

laravel 8 session doesn't save data

I'm trying to save an array for checkout but when i print session it gives null
namespace App\Http\Livewire;
use App\Orders;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Cart;
use Carbon\Carbon;
public function setAmountForCheckout()
{
if(session()->has('coupon'))
{
session()->put('checkout',[
'discount'=>$this->discount,
'subtotal'=>$this->subtotalAfterDiscount,
'total'=>$this->totalAfterDiscount,
]);
}
else
{
session()->put('checkout',[
'discount'=>0,
'tax'=>Cart::instance('cart')->tax(),
'subtotal'=>Cart::instance('cart')->subtotal(),
'total'=>Cart::instance('cart')->total(),
]);
session()->save();
}
}
public function placeOrder(Request $request)
{
dd(session()->get('checkout'));
$this->validate([
'first_name' => 'required|min:4|string',
'Phone_number' => 'required|digits:11'
]);
$order=new Orders();
$order->user_id=Auth::id();
$order->cust_name=$this->first_name;
$order->phone=$this->Phone_number;
$order->subtotal=session()->get('checkout')['subtotal'];
$order->discount=session()->get('checkout')['discount'];
$order->total=session()->get('checkout')['total'];
$order->status='ordered';
$order->is_shipping=$this->haveShipping ? 1:0;
foreach(Cart::instance('cart')->content() as $items)
{
$orderItem= new OrderItems();
$orderItem->product_id=$items->id;
$orderItem->price=$item->price;
$orderItem->order_id=$order->id;
$orderItem->quantity=$item->qty;
$orderItem->save();
}
if($this->haveShipping)
{
$this->validate([
'Address'=>'required|min:4',
'shipping_fee'=>'required|numeric'
]);
$order->address=$this->Address;
$order->delivery=$this->shipping_fee;
}
$order->save();
Cart::instance('cart')->destroy();
session()->forget('checkout');
}
when i remove dd it gives me the error "Trying to access array offset on value of type null"
I'm trying to find what's wrong with the session.
also i have checked the cart if it works or not but i found that it works well and delivers data.
Remove
session()->save();
This is not needed as per https://laravel.com/docs/8.x/session#storing-data

CakePHP3 CRUD API and API Routing

I am using the Friends of Cake CRUD plugin for my back-end API. I am also using API prefixes for my routes:
Router::prefix('Api', function ($routes) {
$routes->extensions(['json', 'xml', 'ajax']);
$routes->resources('Messages');
$routes->resources('ReportedListings');
$routes->fallbacks('InflectedRoute');
});
So far so good. My controller is as follows:
namespace App\Controller\Api;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Core\Exception\Exception;
class MessagesController extends AppController {
use \Crud\Controller\ControllerTrait;
public function initialize() {
parent::initialize();
$this->loadComponent(
'Crud.Crud', [
'actions' => [
'Crud.Add',
'update' => ['className' => 'Crud.Edit']
],
'listeners' => ['Crud.Api'],
]
,'RequestHandler'
);
$this->Crud->config(['listeners.api.exceptionRenderer' => 'App\Error\ExceptionRenderer']);
$this->Crud->addListener('relatedModels', 'Crud.RelatedModels');
}
public function beforeFilter(Event $event){
parent::beforeFilter($event);
}
public function add() {
return $this->Crud->execute();
}
When I make a call as follows:
[POST] /api/messages.json
I get an error:
Action MessagesController::index() could not be found, or is not accessible.
I instead use:
[POST] /messages.json
I don't get the error and I can add a message. So the question is why with my api prefix routing does the CRUD look for index and how can I avoid this behavior?
I found the issue:
Router::prefix('Api', function ($routes) {
....
}
The 'Api' should be lowercase!
Router::prefix('api', function ($routes) {
....
}

Laravel Route::controller routing issue with prefix

I have following implicit route defined (Laravel 5.2)
// Handle locale
Route::group([
'prefix' => '{country}/{language}',
], function () {
Route::controller('user', 'UserController');
});
And here is my controller
class UserController extends BaseLocaleController
{
public function getIndex()
{
return view('user/index');
}
public function getProfile($slug)
{
echo $slug;die;
return view('user/view');
}
}
My URI Structure is
http://{host}/in/en/user/profile/manju
The problem here, my slug value is in instead of manju. Is there any URI pattern I need to apply?
How can make this work in Laravel 5.2. As you could see, I have country and language prefix in Route::group.
Just pass the $country, $language to the method
So it should be
public function getProfile($country, $language, $slug)
{
echo $slug;die;
return view('user/view');
}

Yii2 autologin doesn't work

I try to realize the autologin feature in yii2.
So I've enabled autologin in configuration:
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'loginUrl' => ['account/login', 'account', 'account/index'],
],
Also I've added rememberMe field in form configuration
public function scenarios() {
return [
'login' => ['username','password','rememberMe'],
'activate' => ['password','passwordrepeat'],
'register' => ['username', 'mail'],
'setup' => ['username', 'password', 'passwordrepeat', 'mail', 'secretkey'],
];
}
// ...
[
['rememberMe'],
'boolean',
'on' => 'login',
],
I'm using this now at login:
public function login() {
//var_dump((bool) ($this->rememberMe)); exit();
if (!$this->validate()) {
return false;
}
return Yii::$app->user->login($this->getUser(), (bool) ($this->rememberMe) ? 3600*24*30 : 0);
}
If I log in, users function getAuthKey function is called and a new auth_key is generated.
public function generateAuthKey() {
$this->auth_key = Yii::$app->getSecurity()->generateRandomString();
Helper::save($this);
// Helper is a database helper which will update some rows like last_modified_at and similar in database
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
$this->generateAuthKey();
return $this->auth_key;
}
But always, I log in, it doesn't set some cookie variables.
My cookies are always
console.write_line(document.cookie)
# => "_lcp=a; _lcp2=a; _lcp3=a"
And if I restart my browser I'm not logged in.
What am I doing wrong?
It seems that Yii doesn't work with cookies correctly:
var_dump(Yii::$app->getRequest()->getCookies()); exit();
Results in:
object(yii\web\CookieCollection)#67 (2) { ["readOnly"]=> bool(true) ["_cookies":"yii\web\CookieCollection":private]=> array(0) { } }
If I access via $_COOKIE I have the same values as in JS.
Thanks in advance
I guess you don't have to generate auth key every time in your getAuthKey method. Your app tries to compare database value to the auth key stored in your cookie. Just generate it once before user insert:
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* #inheritdoc
*/
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
if ($insert) {
$this->generateAuthKey();
}
return true;
}
Could be your timeout for autologin is not set
Check if you have a proper assignment to the value assigned to the variable:
$authTimeout;
$absoluteAuthTimeout;
See for more

Authentication with 2 different tables

I need to create a new "auth" config with another table and users. I have one table for the "admin" users and another table for the normal users.
But how can I create another instance of Auth with a different configuration?
While trying to solve this problem myself, I found a much simpler way. I basically created a custom ServiceProvider to replace the default Auth one, which serves as a factory class for Auth, and allows you to have multiple instances for multiple login types. I also stuck it all in a package which can be found here: https://github.com/ollieread/multiauth
It's pretty easy to use really, just replace the AuthServiceProvider in app/config/app.php with Ollieread\Multiauth\MultiauthServiceProvider, then change app/config/auth.php to look something like this:
return array(
'multi' => array(
'account' => array(
'driver' => 'eloquent',
'model' => 'Account'
),
'user' => array(
'driver' => 'database',
'table' => 'users'
)
),
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
Now you can just use Auth the same way as before, but with one slight difference:
Auth::account()->attempt(array(
'email' => $attributes['email'],
'password' => $attributes['password'],
));
Auth::user()->attempt(array(
'email' => $attributes['email'],
'password' => $attributes['password'],
));
Auth::account()->check();
Auth::user()->check();
It also allows you to be logged in as multiple user types simultaneously which was a requirement for a project I was working on. Hope it helps someone other than me.
UPDATE - 27/02/2014
For those of you that are just coming across this answer, I've just recently added support for reminders, which can be accessed in the same factory style way.
You can "emulate" a new Auth class.
Laravel Auth component is basically the Illuminate\Auth\Guard class, and this class have some dependencies.
So, basically you have to create a new Guard class and some facades...
<?php
use Illuminate\Auth\Guard as AuthGuard;
class CilentGuard extends AuthGuard
{
public function getName()
{
return 'login_' . md5('ClientAuth');
}
public function getRecallerName()
{
return 'remember_' . md5('ClientAuth');
}
}
... add a ServiceProvider to initialize this class, passing it's dependencies.
<?php
use Illuminate\Support\ServiceProvider;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Hashing\BcryptHasher;
use Illuminate\Auth\Reminders\PasswordBroker;
use Illuminate\Auth\Reminders\DatabaseReminderRepository;
use ClientGuard;
use ClientAuth;
class ClientServiceProvider extends ServiceProvider
{
public function register()
{
$this->registerAuth();
$this->registerReminders();
}
protected function registerAuth()
{
$this->registerClientCrypt();
$this->registerClientProvider();
$this->registerClientGuard();
}
protected function registerClientCrypt()
{
$this->app['client.auth.crypt'] = $this->app->share(function($app)
{
return new BcryptHasher;
});
}
protected function registerClientProvider()
{
$this->app['client.auth.provider'] = $this->app->share(function($app)
{
return new EloquentUserProvider(
$app['client.auth.crypt'],
'Client'
);
});
}
protected function registerClientGuard()
{
$this->app['client.auth'] = $this->app->share(function($app)
{
$guard = new Guard(
$app['client.auth.provider'],
$app['session.store']
);
$guard->setCookieJar($app['cookie']);
return $guard;
});
}
protected function registerReminders()
{
# DatabaseReminderRepository
$this->registerReminderDatabaseRepository();
# PasswordBroker
$this->app['client.reminder'] = $this->app->share(function($app)
{
return new PasswordBroker(
$app['client.reminder.repository'],
$app['client.auth.provider'],
$app['redirect'],
$app['mailer'],
'emails.client.reminder' // email template for the reminder
);
});
}
protected function registerReminderDatabaseRepository()
{
$this->app['client.reminder.repository'] = $this->app->share(function($app)
{
$connection = $app['db']->connection();
$table = 'client_reminders';
$key = $app['config']['app.key'];
return new DatabaseReminderRepository($connection, $table, $key);
});
}
public function provides()
{
return array(
'client.auth',
'client.auth.provider',
'client.auth.crypt',
'client.reminder.repository',
'client.reminder',
);
}
}
In this Service Provider, I put some example of how to create a 'new' password reminder component to.
Now you need to create two new facades, one for authentication and one for password reminders.
<?php
use Illuminate\Support\Facades\Facade;
class ClientAuth extends Facade
{
protected static function getFacadeAccessor()
{
return 'client.auth';
}
}
and...
<?php
use Illuminate\Support\Facades\Facade;
class ClientPassword extends Facade
{
protected static function getFacadeAccessor()
{
return 'client.reminder';
}
}
Of course, for password reminders, you need to create the table in database, in order to work. In this example, the table name should be client_reminders, as you can see in the registerReminderDatabaseRepository method in the Service Provider. The table structure is the same as the original reminders table.
After that, you can use your ClientAuth the same way you use the Auth class. And the same thing for ClientPassword with the Password class.
ClientAuth::gust();
ClientAuth::attempt(array('email' => $email, 'password' => $password));
ClientPassword::remind($credentials);
Don't forget to add your service provider to the service providers list in the app/config/app.php file.
UPDATE:
If you are using Laravel 4.1, the PasswordBroker doesn't need the Redirect class anymore.
return new PasswordBroker(
$app['client.reminder.repository'],
$app['client.auth.provider'],
$app['mailer'],
'emails.client.reminder' // email template for the reminder
);
UPDATE 2
Laravel 5.2 just introduced multi auth, so this is no longer needed in this version.
Ok, I had the same problem and here is how I solved it:
actually in laravel 4 you can simply change the auth configs at runtime so to do the trick you can simply do the following in your App::before filter:
if ($request->is('admin*'))
{
Config::set('auth.model', 'Admin');
}
this will make the Auth component to use th Admin model when in admin urls. but this will lead to a new problem, because the login session key is the same if you have two users in your admins and users table with the same id you will be able to login to the admin site if you have logged in before as a regular user! so to make the two different authetications completely independent I did this trick:
class AdminGuard extends Guard
{
public function getName()
{
return 'admin_login_'.md5(get_class($this));
}
public function getRecallerName()
{
return 'admin_remember_'.md5(get_class($this));
}
}
Auth::extend('eloquent.admin', function()
{
return new AdminGuard(new EloquentUserProvider(new BcryptHasher, 'Admin'), App::make('session.store'));
});
and change the App::before code to:
if ($request->is('admin*'))
{
Config::set('auth.driver', 'eloquent.admin');
Config::set('auth.model', 'Admin');
}
you can see that I made a new auth driver and rewrote some methods on the Guard class so it will generate different session keys for admin site. then I changed the driver for the admin site. good luck.
I had the same problem yesterday, and I ended up creating a much simpler solution.
My requirements where 2 different tables in two different databases. One table was for admins, the other was for normal users. Also, each table had its own way of hashing. I ended up with the following (Code also available as a gist on Github: https://gist.github.com/Xethron/6790029)
Create a new UserProvider. I called mine MultiUserProvider.php
<?php
// app/libraries/MultiUserProvider.php
use Illuminate\Auth\UserProviderInterface,
Illuminate\Auth\UserInterface,
Illuminate\Auth\GenericUser;
class MultiUserProvider implements UserProviderInterface {
protected $providers;
public function __construct() {
// This should be moved to the config later...
// This is a list of providers that can be used, including
// their user model, hasher class, and hasher options...
$this->providers = array(
'joomla' => array(
'model' => 'JoomlaUser',
'hasher' => 'JoomlaHasher',
)
'another' => array(
'model' => 'AnotherUser',
'hasher' => 'AnotherHasher',
'options' => array(
'username' => 'empolyee_number',
'salt' => 'salt',
)
),
);
}
/**
* Retrieve a user by their unique identifier.
*
* #param mixed $identifier
* #return \Illuminate\Auth\UserInterface|null
*/
public function retrieveById($identifier)
{
// Returns the current provider from the session.
// Should throw an error if there is none...
$provider = Session::get('user.provider');
$user = $this->createModel($this->providers[$provider]['model'])->newQuery()->find($identifier);
if ($user){
$user->provider = $provider;
}
return $user;
}
/**
* Retrieve a user by the given credentials.
*
* #param array $credentials
* #return \Illuminate\Auth\UserInterface|null
*/
public function retrieveByCredentials(array $credentials)
{
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
// Retrieve the provider from the $credentials array.
// Should throw an error if there is none...
$provider = $credentials['provider'];
$query = $this->createModel($this->providers[$provider]['model'])->newQuery();
foreach ($credentials as $key => $value)
{
if ( ! str_contains($key, 'password') && ! str_contains($key, 'provider'))
$query->where($key, $value);
}
$user = $query->first();
if ($user){
Session::put('user.provider', $provider);
$user->provider = $provider;
}
return $user;
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Auth\UserInterface $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserInterface $user, array $credentials)
{
$plain = $credentials['password'];
// Retrieve the provider from the $credentials array.
// Should throw an error if there is none...
$provider = $credentials['provider'];
$options = array();
if (isset($this->providers[$provider]['options'])){
foreach ($this->providers[$provider]['options'] as $key => $value) {
$options[$key] = $user->$value;
}
}
return $this->createModel($this->providers[$provider]['hasher'])
->check($plain, $user->getAuthPassword(), $options);
}
/**
* Create a new instance of a class.
*
* #param string $name Name of the class
* #return Class
*/
public function createModel($name)
{
$class = '\\'.ltrim($name, '\\');
return new $class;
}
}
Then, I told Laravel about my UserProvider by adding the following lines to the top of my app/start/global.php file.
// app/start/global.php
// Add the following few lines to your global.php file
Auth::extend('multi', function($app) {
$provider = new \MultiUserProvider();
return new \Illuminate\Auth\Guard($provider, $app['session']);
});
And then, I told Laravel to use my user provider instead of EloquentUserProvider in app/config/auth.php
'driver' => 'multi',
Now, when I authenticate, I do it like so:
Auth::attempt(array(
'email' => $email,
'password' => $password,
'provider'=>'joomla'
)
)
The class would then use the joomlaUser model, with the joomlaHasher, and no options for the hasher... If using 'another' provider, it will include options for the hasher.
This class was built for what I required but can easily be changed to suite your needs.
PS: Make sure the autoloader can find MultiUserProvider, else it won't work.
I'm using Laravel 5 native auth to handle multiple user tables...
It's not difficult, please check this Gist:
https://gist.github.com/danielcoimbra/64b779b4d9e522bc3373
UPDATE: For Laravel 5, if you need a more robust solution, try this package:
https://github.com/sboo/multiauth
Daniel