Laravel Homestead exception handling/pretty error message display not working - laravel

If there's an error anywhere in my code, such as in the routes file or a view, then instead of displaying the 'pretty' error message I get a dump of JS in the browser.
The error message is in there, but I have to hunt for it.
I'm using Laravel 5.8 in Homestead.
.env has APP_DEBUG=true set. I've also tried directly editing config/app.php to set debug but it doesn't work.
I'm quite new to Laravel so at a loss as to what to look at next...
Here's the first few lines of what gets dumped to the screen, please also check the attached screenshot below.
window.data = {"report":{"notifier":"Laravel Client","language":"PHP","framework_version":"6.0.3","language_version":"7.3.7-2+ubuntu18.04.1+deb.sury.org+1","exception_class":"Facade\\Ignition\\Exceptions\\ViewException","seen_at":1573633009,"message":"htmlspecialchars() expects parameter 1 to be string, array given (View: \/home\/vagrant\/pinyin\/resources\/views\/cards\/cards.blade.php)","glows":[],"solutions":[],"stacktrace":[{"line_number":251,"method":"handleError","class":"Illuminate\\Foundation\\Bootstrap\\HandleExceptions","code_snippet":{"236":"","237":"if (! function_exists(\u0027e\u0027)) {","238":" \/**","239":" * Encode HTML special characters in a string.","240":" *","241":" * #param \\Illuminate\\Contracts\\Support\\Htmlable|string $value","242":" * #param bool $doubleEncode","243":" * #return string","244":" *\/","245":" function e($value, $doubleEncode = true)","246":" {","247":" if ($value instanceof Htmlable)

Found the fix. In the webpack.mix.js file add the following to BrowserSync options:
mix.browserSync({
snippetOptions: {
rule: {
match: /<\/body>/i,
fn: function (snippet, match) {
return snippet + match;
}
}
}
});
Solution from: https://github.com/facade/ignition/issues/16#issuecomment-527260360
Found via: https://github.com/laravel/framework/issues/29909

Related

How get cloudinary file url/other properties by public_id?

Saving images under cloudinary( with cloudinary-laravel 1.0) I keep public_id in my database
and I want to get url(http or https), size, dimaentainal of this file by public_id
At reading this
/**
* You can also retrieve a url if you have a public id
*/
$url = Storage::disk('cloudinary')->url($publicId);
at
https://github.com/cloudinary-labs/cloudinary-laravel
I got ERROR:
Disk [CLOUDINARY] does not have a configured driver.
But I save images to cloudinary with storeOnCloudinaryAs method and in my .env I have
CLOUDINARY_URL=cloudinary://NNNNNNNNNNNN:AErjB_-XXXXXXXXX
CLOUDINARY_UPLOAD_PRESET=ml_default
and default file config/cloudinary.php
My config/filesystems.php has no any cloudinary parameters and can it be reason of my error?
Also it seems very strange for me that Storage::was used in this case, but I did not
find how get file url/other properties by public_id ?
Edited 1:
I added line
...
CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider::class,
...
in 'providers' block of ny config/app.php and cleared cach.
But still got
"Disk [CLOUDINARY] does not have a configured driver."
error.
applying changes into .env and clearing cache I try to debug from which line error is triggered in file vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemManager.php as :
protected function resolve($name)
{
$config = $this->getConfig($name);
\Log::info( varDump($name, ' -1 $name resolve::') ); // IT HAS ‘CLOUDINARY’ value
if (empty($config['driver'])) {
throw new InvalidArgumentException("Disk [{$name}] does not have a configured driver.");
}
But what is source for $config in this file?
config/filesystems.php ? In this file I have no any CLOUDINARY block. maybe I need to add it? But in which format ?
Thanks in advance!
Setting driver to lowercase
$cloudinaryUrl = Storage::disk(strtolower($imagesUploadSource))
fixed this error.

Laravel production error using Guzzle HTTP to get URL status code

I am running into an issue where I'm getting the following error in my laravel.log file.
[2020-12-20 13:43:43] production.ERROR: URI must be a string or UriInterface
However my code works in development, which is super weird. I'm trying to figure out why this isn't working and i'm just really at a loss and no amount of googling or searching here has answered my question as to why in development vs production this error is occuring.
Heres my function:
/**
* Returns the user avatar or the placeholder avatar
* depending on the Discord Status Code
*
* #param \App\Models\Auth\User $user
* #return \Illuminate\Http\RedirectResponse|mixed|string
*/
public static function getUserAvatar(\App\Models\Auth\User $user) {
$client = new Client();
try {
$response = $client->head($user->avatar);
} catch(BadResponseException $e) {
return "https://dummyimage.com/128x128/888ea8/ebedf2.png?text=No+Image+Found";
}
if($response->getStatusCode() == 200) {
return $user->avatar;
} else {
return "https://dummyimage.com/128x128/888ea8/ebedf2.png?text=No+Image+Found";
}
}
The main functionality is this... whenever a User logs in, their avatar updates from discord (using socialite as the login provider). However if the user changes their avatar in discord, but hasn't logged into our site in a while, that avatar link will just go dead as discord no longer wants to serve it. So the avatar link returns a 404 code. I'm basically just trying to handle this 404 code and not display a broken image on the site. Rather it just be a placeholder image instead.
Edit: When i die and dump on $user->avatar I get the following result:
I've also tried the following as well to no avail:
$response = $client->request('GET', (string) $user->avatar, ['allow_redirects' => false, 'verify' => false]);
Thanks.

"ReflectionException Function () does not exist" when trying to setup authentication in Laravel

I'm having some trouble getting authentication working 100% in Laravel (all views seem to work so far except for "home") and was hoping to get some assistance from the Laravel experts out there.
A bit of background info:
PHP Version: 7.3.11
Laravel Version: 8.13.0
Used Composer to build the ui scaffolding (composer require laravel/ui)
Used the Bootstrap ui option (php artisan ui bootstrap --auth)
The issue
As mentioned above, I seem to be able to access all of the generated authentication views so far (login, register & the password reset views), however after registering with a dummy account I get the following error when trying to access the "home" view:
ReflectionException
Function () does not exist
The Stack trace is pointing to the following file:
"vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php:23":
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Reflector;
use Illuminate\Support\Str;
use ReflectionFunction;
use ReflectionMethod;
class RouteSignatureParameters
{
/**
* Extract the route action's signature parameters.
*
* #param array $action
* #param string|null $subClass
* #return array
*/
public static function fromAction(array $action, $subClass = null)
{
$parameters = is_string($action['uses'])
? static::fromClassMethodString($action['uses'])
: (new ReflectionFunction($action['uses']))->getParameters();
return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) {
return Reflector::isParameterSubclassOf($p, $subClass);
});
}
/**
* Get the parameters for the given class / method by string.
*
* #param string $uses
* #return array
*/
protected static function fromClassMethodString($uses)
{
[$class, $method] = Str::parseCallback($uses);
if (! method_exists($class, $method) && Reflector::isCallable($class, $method)) {
return [];
}
return (new ReflectionMethod($class, $method))->getParameters();
}
}
With the following line (line 23) being highlighted as the error:
: (new ReflectionFunction($action['uses']))->getParameters();
And here are the routes used in the "web.php" file:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome', ['pageTitle' => 'Home']);
});
Route::get('/services', function () {
return view('services', ['pageTitle' => 'Services']);
});
Route::get('/contact', function () {
return view('contact', ['pageTitle' => 'Contact']);
});
Auth::routes();
Route::get('/home', ['pageTitle' => 'Client Dashboard'], [App\Http\Controllers\HomeController::class, 'index'])->name('home');
After a bit of googling I've learnt that the method I'm trying to use to setup authentication has been deprecated and it is now advised to use Jetstream or Fortify, however I also found a few examples of people still managing to use this old method in their projects:
https://www.youtube.com/watch?v=NuGBzmHlINQ
As this is my first ever Laravel project I was really trying to just stick with the basics and not over complicate things for myself which is why I chose not to use Jetstream or Fortify and tried to stick to this older approach of setting up authentication. However I've been stuck on this for a couple of hours now and have not been able to figure out what's going wrong which is why I'm now seeking some help with it.
Happy to provide extra details/project code if needed - any help I can get with this would be really appreciated.
Btw, this also happens to be my first ever post on StackOverflow so any feedback on my question or advice on how I can improve it would also be greatly appreciated.
Cheers,
adb
Adjust your last route to include some type of 'action', by removing that second argument (as it only takes 2 arguments):
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
I have changed the web.php file.
I was getting the same error when using the following route:
Route::post('/delete/{id}',[AdminController::class],'destroyProduct');
Changing the route using this code fixed the problem:
Route::post('/delete/{id}','App\Http\Controllers\AdminController#destroyProduct');
I was getting the same error when making a simple route.
Route::get("/test", [ListPagesController::class, "index"]);
This was my code in the web.php file and I was routing my blade file in views via the controller.
When I later redirected it directly to web.php this way without using a controller, the problem was resolved.
Route::get("/test", function () {return view("main");});
I don't quite understand why but the problem is solved.
You Should add it in line 2 web.php
use App\Http\Controllers\YourControllerName;
For me, I changed:
Route::get('/branch/', [Controller::class, 'get_branch_list'])->name('branch');
To:
Route::get('/branch/', 'Controller#get_branch_list')->name('branch');

How enable detailed error messages in Laravel?

I am using Laravel 5.5, and I realized that in this version, the errors seems a bit 'user-friendly'... How to get the detailed error messages again?
For example: before, with this code:
abort(500, 'The server is on fire');
i saw this message "The server is on fire". Now, all I see is "Whoops, looks like something went wrong."
Thanks in advance!
The reason you're getting this error is because you're aborting with a 500 code. What Laravel will eventually do is check if there is a an error view relating to that error code (which there is) and in turn display that view.
Out of the box Laravel comes with a 404, 419, 429, 500, 503 error views.
I would suggest using a code that is more appropriate for your situation (if possible). Here's a list of some of the error codes https://httpstatuses.com/.
Failing that you could override the default behaviour by adding the following to your app/Exceptions/Handler.php class:
/**
* Render the given HttpException.
*
* #param \Symfony\Component\HttpKernel\Exception\HttpException $e
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function renderHttpException(HttpException $e)
{
$status = $e->getStatusCode();
if ($status == 500 && config('app.debug')) {
return $this->convertExceptionToResponse($e);
}
return parent::renderHttpException($e);
Essentially, this will bypass looking for the 500.blade.php error view and should then display the stack with whoops. Please note that this is not tested against an actual 500 error so I'm not sure if it will work for that (I can't think of why it wouldn't but I just wanted to mention it).

Check line existence in laravel's trans()

Lets say in my lang/en/general.php there are multiple translation lines for example:
"token" => "This password reset token is invalid.",
"sent" => "Password reminder sent!",
"reset" => "Password has been reset!",
But in my lang/de/general.php these lines are missing.
So later, when I use the Lang::get('general.token') or simply trans('general.token')
The english version will return
This password reset token is invalid.
And the german (de) version will return
general.token
Is there any way I can handle a 'translation not found' function, like a filter but not creating a special class for it? For example, when a line has no translation, I want to throw an Exception.
Thanks in advance!
In Laravel 4 only, you can use Lang::has() as below, here is the doc
if (\Lang::has('general.token')) {
// line exists.
} else {
// line not exist.
}
In current Laravel versions you can just use trans helper like so:
#if (trans()->has('general.token'))
{{ trans('general.token') }}
#endif
This question is getting a little bit old but as per version 5.8 you can simply check as this :
array_key_exists('your-word-key', trans('your-file'))
or
array_key_exists('your-word-key', trans('your-file.array_key'))
for nested translations
You might want to write a helper similar to the one below to help with fallbacks:
/**
* Makes translation fall back to specified value if definition does not exist
*
* #param string $key
* #param null|string $fallback
* #param null|string $locale
* #param array|null $replace
*
* #return array|\Illuminate\Contracts\Translation\Translator|null|string
*/
function trans_fb(string $key, ?string $fallback = null, ?string $locale = null, ?array $replace = [])
{
if (\Illuminate\Support\Facades\Lang::has($key, $locale)) {
return trans($key, $replace, $locale);
}
return $fallback;
}
Note: The helper only works on PHP 7.1 (which has support nullable types). Adjust it to your PHP version if it's lower than 7.1.
You can create your own TranslationServiceProvider and Translator and override the get() method in translator to throw an exception when the parent::get() returns a translation string that is equal to the translation key that was passed in. Both #lang() and trans() functions call the get() method of the translator.
Seems like a whole lot of trouble only to get another reason for a "Whoops! something went wrong!" on your site. You will only get the exception when the translation is encountered.
Another solution: you can use the barryvdh/laravel-translation-manager package, it has a translation service provider that logs missing translation keys and a web interface for managing translations. It will log missing translation keys per locale and let you edit them through a web interface.
It is simple to setup and easy to modify. So you can replace the logging with throwing an exception.

Resources