Laravel memcached errors after random time - laravel

Hello I am using memcached in laravel application 5.8.
After some time the error is:
production.ERROR: Invalid argument supplied for foreach()
Code in controller is:
$page = \Request::get('page', '0');
Cache::tags('posts')->remember('page-'.$page, 15, function(){
return Post::orderBy('created_at', 'desc')
->paginate(20);
});
$posts = Cache::tags('posts')->get('page-'.$page);
The error comes, because of the #foreach loop in the view.
When I get the error, I can fix it by restarting the server, but this is not really a good solution. How can I prevent this issue and still use memcached?
I am sure that it comes from the cache, because if I change the cache driver to array than the error is gone.
Update:
So I have tried to change from remember to rememberForever in controller, but the problem remains. It errors and only solution is to turn off cache or reboot server. Otherwise it is giving me production.ERROR: Invalid argument supplied for foreach().

Related

How can I get Google Auth working with Laravel?

I'd like to know if there's an easy fix for this error that I'm getting while trying to add support for Google sign-in to my website, since I can only reproduce it while on a Laravel-based environment. Vanilla PHP applications do run just fine.
This is my relevant code:
if ($request->has('googleToken')) {
$client = new Google_Client(['client_id' => env('GOOGLE_PLATFORM_CLIENT_ID') ]);
$payload = $client->verifyIdToken($credentials['googleToken']);
if (!$payload) {
return response([ 'error' => 'Invalid token, please try using form-based authentication.' ], Response::HTTP_FAILED_DEPENDENCY);
}
$user['googleToken'] = $credentials['googleToken'];
}
I know I'm doing too relaxed validations, but please just focus on the fact that I'm just testing and I plan to change this code in the near future.
The code above, receives its data through an Axios PUT request from the frontend with the payload looking like this:
{
googleToken: "eyJhbGciOiJSUzI1NiIsImtpZCI6IjE5ZmUyYTdiNjc5NTIzOTYwNmNhMGE3NTA3OTRhN2JkOWZkOTU5NjEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiNTkyODkzNjE3ODYzLXRscDdvaDByaTk2dTZxZGxrOXYwbHAyanQyNDlkdDNsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXVkIjoiNTkyODkzNjE3ODYzLXRscDdvaDByaTk2dTZxZGxrOXYwbHAyanQyNDlkdDNsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwic3ViIjoiMTE1NTg0MDg0NTE2OTMxOTQzODU..."
mailAddress: "user#mail.com"
}
The problem is that the payload would simply return false. I decided to try to investigate the issue, so I went to the definition of verifyIdToken contained within Google_Client and, from there, jumped over to the function that finally returns to its parent, which is verifyIdToken from the class Verify.
Inside of that class, there's a pretty loose try/catch block in which I decided to try adding a generic exception case so that I could quickly print the error message for debugging. I did, and this is the output I got:
OpenSSL unable to verify data: error:0909006C:PEM routines:get_name:no start line
This is what's failing internally, and from this point on, I don't really have an idea about how to proceed since the error feels very cryptic, or at least it's not in my field of knowledge.
The OpenSSL error you quoted indicates that your client was not able to read any/further PEM-encoded data. Refer to https://www.openssl.org/docs/man1.1.1/man3/PEM_read.html.
OpenSSL unable to verify data: error:0909006C:PEM routines:get_name:no start line
Here,
'PEM routines' represents the library within OpenSSL
'get_name' is the function
'no start line' is the reason
Is you client able to access the necessary certificates/keys?

Laravel 502 Proxy Error on specific route call

I am having a problem specific to the production code. On said server, everytime I try to access specific route which is supposed to show a table of all categories I get a 502 Proxy Error:
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request
Reason: Error reading from remote server
I have found some common problem on the internet already, however all of those were for users who use nginx. I use Laragon. Also, Laravel version is 5.5.21
As I said the problem is production code only. It is not happening when I run it locally.
I also tried to download laravel.log file from the server, but there was nothing there.
This is the function that is being called by route:
public function index(){
if(empty(request()->query()) && session()->exists('categories_filter')){
return redirect(route('categories.index').'?'.http_build_query(session()->pull('categories_filter')));
}
if(!empty(request()->query())){
$this->store_filter();
}
$categories = Category::orderBy($this->sort, $this->order);
if($name_sk = request('name_sk')){
$categories = $categories->where('name_sk', 'like', "%{$name_sk}%");
}
$categories = $categories->paginate(20);
$all_categories = Category::with('children')->get();
$sort = $this->sort;
$order = $this->order;
$new_order = $this->new_order;
return view('admin.categories.index', compact('categories', 'sort', 'order', 'new_order', 'all_categories'));
}
I honestly have no idea where the problem lies or what is its cause.
So to the people who have a similar problem, here is where my problem was:
I had a recursive blade partial component, that called itself and in every single one of those there was a sql query executed. I had to completely remake that part of my view.
So to explain it, the reason for this error is simply that I was sending too many requests to the database asking for a single row. This was a problem because once there was a moderate amount of data, it was simply taking way too long to load.

How to have usefull debugging or error messages from laravel

I'm a bit new to laravel, but I'm experienced in Php.
In previous works, I set a mecanism that allowed me to be informed when nearly any problem occurred on the server:
I got full stack
precise PHP error messages
for nearly all king of errors
a mail sent to me
So when I began to work with laravel, I tried to do the same things, and achieved:
full stack
a mail sent to me
But I can't have meaningful error in all case. One example:
$store = Store::create(...)
In this line I forget to specify the namespace (\App\Store::create), and I get those error messages:
first:
FatalThrowableError ; Type error: Argument 1 passed to App\Http\Controllers\User::create() must be an instance of Illuminate\Http\Request, array given, called in /var/www/html/laravel/blog/app/Http/Controllers/User.php on line 94
second:
ErrorException ; Trying to get property of non-object in VerifyCsrfToken.php (line 156)
third:
FatalThrowableError ; Type error: Argument 1 passed to Illuminate\Session\Middleware\StartSession::addCookieToResponse() must be an instance of Symfony\Component\HttpFoundation\Response, array given, called in /var/www/html/laravel/blog/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php on line 72
I understand that laravel is a complex framework but I can't figure why it produces this errors, and how I can have more useful errors (as as it is I can only know that "something is bad").
Has someone an idea ?
ยน There is some errors that Php prefers to keep to himself (in its logs) :-)
When you start a new Laravel project, error and exception handling is
already configured for you. The App\Exceptions\Handler class is where
all exceptions triggered by your application are logged and then
rendered back to the user.
https://laravel.com/docs/5.4/errors
I recommend you to dive into the official docs and into your App\Exceptions\Handler.
Maybe you are looking for report and render methods in that class.
I finally cornered the problem and I learned a lot.
I thank for their benevolence #Don't Panic and #Vitalmax !
The error was that I forgot that PHP namespaces are case insensitive: in my post I cleaned a bit the code as I knew that it didn't stick to the code's conventions (a controller's name must begin with a capital letter). Originally my controller name was user and the faulty code was:
$user = User::create(...)
As you can guess PHP believed that I wanted to call user::create (as I have such a method in my controller) and not User::create (as I wanted).
What I learned:
don't alter the code when asking for help
Laravel use a cache system that can get in the way of the debugging (see a question that I asked on laracast's forum )
take more time to read the error message; I know this rule but I keep doing otherwise

Migrating to Laravel 5, route:cache throwing exception

Moving from Laravel 4.2 to 5.0
We have about ~200 routes in our API, most of them were Closures. So I've spent the better part of the last couple days converting them all to controller routes. Everything is back to being stable, but when I try to run php artisan route:cache it throws an exception
[Exception]
Serialization of 'Closure' is not allowed
I did a ctrl+f for function, and the only ones left in the routes file are the two Route::group entries (which, yes, are closures...but surely only routes count...).
Any guidance? After the tediousness of the last two days, this error is...not what I wanted to see.
EDIT: Full stacktrace
Route cache cleared!
[Exception]
Serialization of 'Closure' is not allowed
Exception trace:
() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\laravel\framework\src\Illuminate\Foundation\Console\RouteCacheCommand.php:95
serialize() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\laravel\framework\src\Illuminate\Foundation\Console\RouteCacheCommand.php:95
Illuminate\Foundation\Console\RouteCacheCommand->buildRouteCacheFile() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\laravel\framework\src\Illuminate\Foundation\Console\RouteCacheCommand.php:65
Illuminate\Foundation\Console\RouteCacheCommand->fire() at n/a:n/a
call_user_func_array() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\laravel\framework\src\Illuminate\Container\Container.php:523
Illuminate\Container\Container->call() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\laravel\framework\src\Illuminate\Console\Command.php:115
Illuminate\Console\Command->execute() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\symfony\console\Symfony\Component\Console\Command\Command.php:257
Symfony\Component\Console\Command\Command->run() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\laravel\framework\src\Illuminate\Console\Command.php:101
Illuminate\Console\Command->run() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\symfony\console\Symfony\Component\Console\Application.php:874
Symfony\Component\Console\Application->doRunCommand() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\symfony\console\Symfony\Component\Console\Application.php:195
Symfony\Component\Console\Application->doRun() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\symfony\console\Symfony\Component\Console\Application.php:126
Symfony\Component\Console\Application->run() at C:\Users\cjtho_000\Desktop\ecapi_l5\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:94
Illuminate\Foundation\Console\Kernel->handle() at C:\Users\cjtho_000\Desktop\ecapi_l5\artisan:36
EDIT 2: removed the route groups to test, still throws the exception
Turns out, the entirely unhelpful error message was trying to tell me that I had a duplicate route (copy paste error, I had two get routes matching the same uri).
Removing the duplicate fixed the issue.
Per your stack trace,
vendor\laravel\framework\src\Illuminate\Foundation\Console\RouteCacheCommand.php:95
serialize() at vendor\laravel\framework\src\Illuminate\Foundation\Console\RouteCacheCommand.php:95
Laravel is trying to serialize the routes collection on line 95 of RouteCacheCommand.php.
The error you're getting
Serialization of 'Closure' is not allowed
looks like its PHP's standard "someone tried to serialize an anonymous function" exception message (vs. it might be a custom Laravel exception).
All this means something is adding an anonymous function (i.e. "closure") to your route collection. If you're 100% sure you've removed them all from routes.php, my guess would be the route's in third party code somewhere.
It's best not to guess. Try some debugging code that's something like the following
//un-tested pseudo debugging code
//get the application's routes, using the same
//technique as the route:cache command
$app = require /path/to/your/laravel/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
$routes = $app['router']->getRoutes();
//go through each route
foreach($routes as $route)
{
//if the route is a closure
if(is_object($route) && ($route instanceof Closure))
{
//use reflection to find out which file the closure is defined in
$r = new ReflectionFunction($route);
var_dump($route->getFileName ());
}
}
This will let you figure out where the closure that's causing your problems is defined, which should be enough to point to the problem.

Passing data to view in laravel

I have the following code
$input = Input::all();
$this->agro->create($input);
$alldata = $this->agro->all();
return View::make('agro.showdata',['myalldata'=>$alldata]);
Here when I return $alldata, all data from database is displayed.I guess here all the data is stored in $alldata variable which we are passing to the showdata view file in the variable myalldata.
Now when in myalldata, if data is not accesses it works as
<h1>DIsplaying data </h1>
But when I try to display data, it gives error Whoops, looks like something went wrong
ie
<h1>Displaying data from database<h1>
{{ $myalldata->title }}
Please help display the data from database.
Another thing, every time something is wrong, it gives error Whoops, looks like something went wrong.How to debug laravel to know where things are going wrong?
It appears that $myalldata is an array of elements. To access each one, you'd need to use a for-loop, like such, in your view:
#foreach($myalldata as $row)
<div>{{{ $row->title }}}</div>
#endforeach
You can determine whether to display the full error trace by modifying your application's app/config/app.php file, and replacing
'debug' => false,
with
'debug' => true,
Keep in mind that, in a production environment (when clients can access the site), you'll want to disable debug mode.
How to debug laravel to know where things are going wrong?
Go to your config/app.php or config/yourEnvironment/app.php and set Application Debug Mode to true.
'debug' => true,

Resources