Here's a way to encode a Laravel site request as JSON to log it via Laravel's logging mechanism, using the Log
class from the illuminate/support
package1.
// Log parameters in a get request
Route::get('a-view', function(Request $request) {
\Log::info(json_encode(request()->server()));
return view('your.view');
});
// Log parameters in a get request and redirect
Route::get('redirect', function(Request $request) {
\Log::info(json_encode(request()->server()));
return redirect('/some/page');
});
The service provider of Laravel's Log
class is Illuminate\Support\Facades\Log
. ↩
You can use the parse_url
built-in PHP method to break down a URL into its components.
here's the method itself.
parse_url(string $url, int $component = -1): int|string|array|null|false
And here's how to use it.
parse_url("https://gettingsimple.com/podcast");
// [
// "scheme" => "https",
// "host" => "gettingsimple.com",
// "path" => "/podcast",
// ]
You can then obtain the scheme
, host
, or path
of a URL.
$components = parse_url("https://gettingsimple.com/podcast");
$scheme = $components["scheme"];
// "https"
$host = $components["host"];
// "gettingsimple.com"
$path = $components["path"];
// "/podcast"
Here's how to upgrade to a new version of PHP's Mongo extension if you previously installed it but you've upgraded to the latest PHP version. (If you haven't, see how to install it.)
Uninstall the existing mongodb
extension.
sudo pecl uninstall MongoDB
# Extension mongodb disabled in php.ini
# uninstall ok: channel://pecl.php.net/mongodb-1.13.0
Then follow this guide to install it again for the latest PHP version.
Here's an easy way to retrieve the PHP version your Laravel app is running.
>>> PHP_VERSION
=> "8.1.8"
PHP's ucwords()
function converts a phrase to title case.
// PHP
ucwords('a big snake')
// Returns "A Big Snake"
You can obtain the same result in Python with the .title()
string method.
# Python
"a big snake".title()
# Returns "A Big Snake"
Here's how to test this function in the command-line interface.
python -c "print('nono martinez alonso'.title())"
When trying to send an email using Amazon SES (Simple Email Service) using Laravel's Mail
class.
\Mail::send('email', [], function ($message) {
$message
->from('from@gmail.com', 'John Appleseed')
->to('to@gmail.com', 'Nono Martínez Alonso')
->subject('A sample email')
->html('<p>Hello, this is a test email.</p>');
});
I got the following error.
Expected response code "250" but got code "530",
with message "530 5.7.1 Authentication required".
You need to configure the following environment variables in .env
.
AWS_ACCESS_KEY_ID=XXXXXXXXXXXXXX
AWS_SECRET_ACCESS_KEY=XXXXXXXXXX
AWS_DEFAULT_REGION=us-east-1
And then in config/services.php
.
<?php
return [
// ...
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];
Lastly, set Amazon SES as Laravel's default mailer in .env
.
MAIL_MAILER=ses
Note that you could also set the default in your config/mail.php
in case there's no MAIL_MAILER
key in your .env
file.
<?php
return [
// ...
'default' => env('MAIL_MAILER', 'ses'),
This is the last error I got before everything worked.
Request to AWS SES API failed.
Email address is not verified.
The following identities failed the check in region US-EAST-1.
I was sending from an unverified email address. Changing it to one of my verified accounts fixed the issue.
This page is incomplete
An option is to set CACHE=array
on your .env file.
I need to learn why this happens and what other alternatives there are to avoid this error.
This happened to me when installing laravel-geoip
https://github.com/Torann/laravel-geoip/issues/123
It makes sense that you don't want to change your cache type if you're using file
or database
to array
simply to use a function in this package.
Other users recommended to publish tarenn/geoip
's config file and disable caching and tagging.
# Publish the configuration file
php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config
# Copied File [/vendor/torann/geoip/config/geoip.php] To [/config/geoip.php]
# Publishing complete.
// ...
'cache' => 'none', // defaults to 'all'
// ...
'cache_tags' => [], // defaults to // ['torann-geoip-location']
// ...
Another option is to conditionally set the tag.
// ...
'cache_tags' => env('CACHE_DRIVER') == "array" ? ['torann-geoip-location'] : null,
// ...
If you're receiving this error when trying to composer install
.
Your GitHub OAuth token for github.com contains invalid characters
The solution is to update Composer to the latest version, which supports the new token format, as suggested by Jordi Boggiano on this tweet. "Composer 1.10.21 and 2.0.12 (both released April 1st) added support for the new GitHub token format."
phar
The following command will install the latest version of Composer on your machine—v2.2.6
as of this writing. Note that future Composer updates will break the script as shown here, as the sha384 hash check won't pass.
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '906a84df04cea2aa72f40b5f787e49f22d4c2f19492ac310e8cba5b96ac8b64115ac402c8cd292b8a03482574915d1a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
You can use Homebrew to install (or reinstall) composer on macOS.
brew install composer
brew reinstall composer
2021.04.20
As I mentioned above, both Lukas Kahwe Smith and Jordi Boggiano discouraged tinkering with Composer's auth.json
file manually and recommended upgrading Composer to its latest version instead.
Still, here's the brute-force fix that worked for me. Apparently, editing the auth.json
is the only way to update to the latest Composer programmatically, and you can revert it to its original state if you opt for this option. The alternative, of course, is to upgrade as shown above.
Edit the composer authentication configuration file ~/.composer/auth.json
.
nano ~/.composer/auth.json
Then replace the following.
"github-oauth": {
"github.com": "ghp_[YOUR-PERSONAL-TOKEN]"
}
With this (basic auth):
"http-basic": {
"github.com": {
"username": "[YOUR-GITHUB-USERNAME]",
"password": "ghp_[YOUR-PERSONAL-TOKEN]"
}
}
To Lukas Kahwe Smith and Jordi Boggiano for pointing this out on Twitter.
I found this error while trying to update and install composer packages with composer install
.
could not find driver (SQL: select * from information_schema.tables where table_schema = folio_burns and table_name = folio_items and table_type = 'BASE TABLE')
At first, I thought the solution was to edit /etc/php/7.4/cli/php.ini
(for PHP-FPM 7.4 in my case) and uncomment the line ;extension=pdo_mysql
to be like extension=pdo_mysql
. But I was still getting this error as the mysql
extension was missing.
PHP Warning: PHP Startup: Unable to load dynamic library 'pdo_mysql' (tried: /usr/lib/php/20190902/pdo_mysql (/usr/lib/php/20190902/pdo_mysql: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/pdo_mysql.so (/usr/lib/php/20190902/pdo_mysql.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
The solution ended up being to install the extension, which would also add its own .ini
file and activate itself on installation.
sudo apt-get install -y php7.4-mysql
Note that you can run this command with multiple extensions to be installed at once.
sudo apt-get install -y php7.4-{xml,bcmath,gd,mbstring,xsl,zip,curl,mysql}
Here's how to get the raw String
value of a Stringable
object. Laravel's Illuminate\Support\Stringable
has lots of helper functions, but sometimes you want to get the raw string value. For that, you just need to use the strval
PHP built-in function on an object of the Stringable
class.
// Define Stringable object
$stringable = Str::of('laravel-stringable-to-string');
get_class($stringable); // returns Illuminate\Support\Stringable
gettype($stringable); // returns object
// Get its raw String value
$string = strval($stringable);
get_class($string); // returns PHP Warning: get_class() expects parameter 1 to be object, string given in […]
gettype($string); // returns string
I was getting this error in Laravel as I created a new app using the latest version (that is 6.2
). Not sure why, the class would work locally but not remotely (on a deployment running in Ubuntu 18.04.3 on DigitalOcean to be precise).
I was using \ResourceBundle::getLocales('')
to get a list of valid locales present on a website and then using in_array($needle, $array)
to check whether a given locale is valid in PHP.
Here's how I fixed it.
composer require symfony/intl
to install Symfony's Intl component.in_array
calls with \Symfony\Component\Intl\Locales::exists($translation)
.
$output = preg_replace('!\s+!', ' ', $input);
From StackOverflow.
Laravel is a powerful PHP framework. Like many other PHP systems, it benefits from the use of Composer to manage its dependencies, making the use of open-source libraries extremely simple.
What follows is a list of the packages (or dependencies) I am using in most of my current projects—let me explain you why.
A package I discovered a few weeks ago. It gives your Laravel app the possibility of adding translations for your SQL tables to various different languages, with a really flexible structure. You can, for instance, have the articles in your blog written in English by default, and only translate to certain languages the ones you want.
Then, you can show those translated languages for users that have selected that locale on their browser, but fallback to the default language if an article is not available in their language.
A package based in Carbon. It makes ridiculously simple working with dates, with support for all languages.
Some of the features I use the most are: parsing database dates to human-readable ones (2015-06-14 could be translated to Sunday 14, June 2015); expressing how long ago a content was created (posted 2 minutes ago, for instance); calculating dates in the past or in the future, by adding or substracting days, weeks, months (or whatever unit) to a date object.
Possibilities are unlimited, and this library makes it even easier that before.
With this package, you can use the Taggable trait to any of your models, and start tagging them. Then, you can use the query builder with its own methods to filter your content depending on tags.
I have been using it for articles and projects, to organize content and allow users to navigate by article categories.
If you are designing with SCSS, you need a parser o automate the generation of your CSS files. This package does the job for me pretty well.
It allows you to run inline PHP functions specifying what SCSS folder to parse, and where to save the CSS. Also, it has an in-built function to minify your CSS files, compressing them a lot, so you don’t have to worry about it.
For development purposes, I tend to set a GET variable on the App::before() filter function (located on app/filters.php) to force generate new CSS files. Running the URL /home/?scss=1, for instance, would regenerate all my CSS files.
Based on Michelf’s PHP parser, this package implements methods to parse Markdown text from strings or files directly.
One example would be calling Markdown::string($string) in your code to parse the $string from markdown to HTML.
—
If you know other PHP packages that I should know of, please drop me a tweet! Thanks for reading.
Following the series of Laravel posts, here is how to make a Laravel app adapt to whatever language the visitor has set as a preference on its browser, or how to show a default language in case your website does not support your visitor's language.
When localizing a website, I usually use the following process:
To achieve this, the first thing we need to do is add the following lines inside the App::before method, on the file app/filters.php:
App::before(function($request)
{
// Set the locale of the app to the user's browser language
$browser_lang = substr(Request::server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
App::setLocale($browser_lang);
});
This will set the language to whatever first language the user browser has selected.
Then, set the fallback_locale variable inside the app/config/app.php to 'en', which will do for the falling back.
And that's it. Now just use the lang/ folder to add different language files in subfolders with their language code (i.e. lang/en/help.php for English, and lang/es/help.php for Spanish).
The strings inside the file should be wrapped in a PHP array, as follows:
<?php
return array(
'terms' => 'términos',
'help' => 'ayuda',
'items' => 'artículos',
);
Lastly, you can use anywhere in your Laravel app the strings inside the help.php file, just by writing trans('help.terms'), for instance—which is a shorthand for Lang::get('help.terms'). That code, will get the terms value corresponding to the user’s language, or to the fallback language if the user’s language does not exist.