Log Laravel

You can easily log your data in Larave, all you have to do is to use Log, and then log whatever you want, here is an example

<?php
 
namespace App\Http\Controllers;
 
use Log;
use App\User;
use App\Http\Controllers\Controller;
 
class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        Log::info('User ID: '.$id);
 
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

You can also use an array of contextual data

Log::info('User failed to login.', ['id' => $user->id]);

Laravel provides 8 levels of logging

Log::emergency($error);
Log::alert($error);
Log::critical($error);
Log::error($error);
Log::warning($error);
Log::notice($error);
Log::info($error);
Log::debug($error);

You can view the log file at: storage/laravel.log but you may find a huge file with thousands of line as this is the main file where all the logs are saved.

If you want to create your own log file, you will need to add a new channel in the config/logging.php

'channels' => [
        'myLog' => [
                    'driver' => 'single',
                    'path' => storage_path('logs/myLog.log'),
                    'level' => 'info',
                ],

where myLog.log is the file name you want to save your logs in

To write to your custom log file, you have to specify the channel you just created

Log::channel('myLog')->info('This is testing for my log file.');

ps. Don’t forget to empty the config cache for the updates to be active

from your terminal, you write: php artisan cache:clear

Finally, when you open myLog.log file, you will see something like this:

[2022-08-25 09:13:20] local.INFO: This is testing for my log file.

API request not working locally but works fine on the server

If you are trying to get some data from an external API and it is working on the Postman or on the live server but is not working locally, and you may also face an error like:

SSL certificate problem: unable to get local issuer certificate

here is a quick solution for this issue:

Change it to:

curl.cainfo = “C:\wamp64\bin\php\php8.1.0\cacert.pem

  • Make sure you remove the semicolon at the beginning of the line and double-check the path of the php folder
  • Save changes to php.ini,
  • Restart WampServer (or any other local server you have)

Create your own custom Excel function

If you want to make your own function as the built-in ones SUM() for example you go to:
Developer tab and click on the Visual Basic icon

in the new window of Microsoft Visual Basic for Applications, you click on Insert > Module

Now you can write your code, for example, if you want to write a function that extracts the url of a link in a cell, the code could be like this

Function GetURL(cell As Range)
    GetURL = cell.Hyperlinks(1).Address
End Function

Now, you can use this function “GetURL” as any ordinary function in Excel.

Note that if you want to save the file, you have to save it as Excel Macro-Enabled Workbook (*.xlsm)

Visit this page for more information:

https://support.microsoft.com/en-us/office/create-custom-functions-in-excel-2f06c10b-3622-40d6-a1b2-b6748ae8231f

Laravel / PHP SOS

When your code is not working right and you have no idea what is wrong:

  • What is the language ?
    Yes, you heard me right, sometimes when you are writing javascript code inside a laravel/php page ..things could get mixed up
  • Remove the cache
    There are lots of cache types you need to clear depending on what you have changed, here are some commands to use:
    • php artisan config:cache
    • php artisan route:cache
    • php artisan view:cache
    • php artisan cache:clear
    • php artisan clear-compiled
    • composer dump-autoload
    • php artisan debugbar:clear
    • php artisan optimize
  • What is the type of the variables ?
    When you want to compare 2 variables and you are sure the result should be true, check the type of the variables, sometimes you could find that you are comparing a variable to an object or collection

How to send a set of customized emails using Gmail and Google sheets without any third-party tools

If you have a list of email addresses and want to send a customized email for each one you can use Google Apps Script to get emails and data from Google sheet and use a draft email in Gmail. Data in Google sheet can be used as variables, ie. {{email}} , {{user name}}, {{password}}

Here is a link with a ready-made code to use:

https://developers.google.com/apps-script/samples/automations/mail-merge

How to use “OR” while searching in datatables js

If you want to search for any of multiple strings in datatables , you can use the regex option, here is an example

 table.columns( 3 ).search('string A| String B', true, false).draw();

3 is the index of the column you want to search

String A, String B are the 2 strings you want to search any of them

true: to indicate that you want to use regex

false : tell datatables not to use smart search option as it uses regex and may conflict with the regex you are using

How to view raw SQL of Laravel query?

There are a number of ways to view the raw SQL statement of your Larael query builder

->dd()

A simple way to show you the SQL statement along with its binding is replacing ->get(), first(), .. with ->dd(), here is an example:

$users = User::select('name')
                  ->where('id', '<', 20)
                  ->where('is_active', 1)
                  ->dd();

and the output will be like this:

"select `name` from `users` where `id` < ? and `is_active` = ?"
array:2 [â–¼
  0 => 20
  1 => 1
]
Continue reading “How to view raw SQL of Laravel query?”

PHP mail is not working

If you are trying to send emails using PHP but nothing is sent, here is a nice StackOverflow reply that covers most of the potential causes.

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

There are a variety of reasons your script appears to not be sending emails. It’s difficult to diagnose these things unless there is an obvious syntax error. Without one you need to run through the checklist below to find any potential pitfalls you may be encountering.

Make sure error reporting is enabled and set to report all errors

Error reporting is essential to rooting out bugs in your code and general errors that PHP encounters. Error reporting needs to be enabled to receive these errors. Placing the following code at the top of your PHP files (or in a master configuration file) will enable error reporting.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP? â€” this answer for more details on this.

Make sure the mail() function is called

It may seem silly but a common error is to forget to actually place the mail() function in your code. Make sure it is there and not commented out.

Make sure the mail() function is called correctly

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call to mail() does not have at least three parameters it will fail.

If your call to mail() does not have the correct parameters in the correct order it will also fail.

Check the server’s mail logs

Your web server should be logging all attempts to send emails through it. The location of these logs will vary (you may need to ask your server administrator where they are located) but they can commonly be found in a user’s root directory under logs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

Don’t use the error suppression operator

When the error suppression operator @ is prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. There are circumstances where using this operator is necessary but sending mail is not one of them.

If your code contains @mail(...) then you may be hiding important error messages that will help you debug this. Remove the @ and see if any errors are reported.

It’s only advisable when you check with error_get_last() right afterwards for concrete failures.

Check the mail() return value

The mail() function:

Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise. It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

This is important to note because:

  • If you receive a FALSE return value you know the error lies with your server accepting your mail. This probably isn’t a coding issue but a server configuration issue. You need to speak to your system administrator to find out why this is happening.
  • If you receive a TRUE return value it does not mean your email will definitely be sent. It just means the email was sent to its respective handler on the server successfully by PHP. There are still more points of failure outside of PHP’s control that can cause the email to not be sent.

So FALSE will help point you in the right direction whereas TRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

Check spam folders; prevent emails from being flagged as spam

Oftentimes, for various reasons, emails sent through PHP (and other server-side programming languages) end up in a recipient’s spam folder. Always check there before troubleshooting your code.

To avoid mail sent through PHP from being sent to a recipient’s spam folder, there are various things you can do, both in your PHP code and otherwise, to minimize the chances your emails are marked as spam. Good tips from Michiel de Mare include:

  • Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site.
  • Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail.
  • Make sure that the IP-address that you’re using is not on a blacklist
  • Make sure that the reply-to address is a valid, existing address.
  • Use the full, real name of the addressee in the To field, not just the email-address (e.g. "John Smith" <john@blacksmiths-international.com> ).
  • Monitor your abuse accounts, such as abuse@yourdomain.com and postmaster@yourdomain.com. That means – make sure that these accounts exist, read what’s sent to them, and act on complaints.
  • Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation.

See How do you make sure email you send programmatically is not automatically marked as spam? for more on this topic.

Make sure all mail headers are supplied

Some spam software will reject mail if it is missing common headers such as “From” and “Reply-to”:

$headers = array("From: from@example.com",
    "Reply-To: replyto@example.com",
    "X-Mailer: PHP/" . PHP_VERSION
);
$headers = implode("\r\n", $headers);
mail($to, $subject, $message, $headers);

Make sure mail headers have no syntax errors

Invalid headers are just as bad as having no headers. One incorrect character could be all it takes to derail your email. Double-check to make sure your syntax is correct as PHP will not catch these errors for you.

$headers = array("From from@example.com", // missing colon
    "Reply To: replyto@example.com",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don’t use a faux From: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails with From: sender domains it’s not configured for.

Make sure the recipient value is correct

Sometimes the problem is as simple as having an incorrect value for the recipient of the email. This can be due to using an incorrect variable.

$to = 'user@example.com';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into the mail() function call:

mail('user@example.com', $subject, $message, $headers); 

This can apply to all of the mail() parameters.

Send to multiple accounts

To help rule out email account issues, send your email to multiple email accounts at different email providers. If your emails are not arriving at a user’s Gmail account, send the same emails to a Yahoo account, a Hotmail account, and a regular POP3 account (like your ISP-provided email account).

If the emails arrive at all or some of the other email accounts, you know your code is sending emails but it is likely that the email account provider is blocking them for some reason. If the email does not arrive at any email account, the problem is more likely to be related to your code.

Make sure the code matches the form method

If you have set your form method to POST, make sure you are using $_POST to look for your form values. If you have set it to GET or didn’t set it at all, make sure you use $_GET to look for your form values.

Make sure your form action value points to the correct location

Make sure your form action attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

Make sure the Web host supports sending email

Some Web hosting providers do not allow or enable the sending of emails through their servers. The reasons for this may vary but if they have disabled the sending of mail you will need to use an alternative method that uses a third party to send those emails for you.

An email to their technical support (after a trip to their online support or FAQ) should clarify if email capabilities are available on your server.

Make sure the localhost mail server is configured

If you are developing on your local workstation using WAMP, MAMP, or XAMPP, an email server is probably not installed on your workstation. Without one, PHP cannot send mail by default.

You can overcome this by installing a basic mail server. For Windows you can use the free Mercury Mail.

You can also use SMTP to send your emails. See this great answer from Vikas Dwivedi to learn how to do this.

Enable PHP’s custom mail.log

In addition to your MTA’s and PHP’s log file, you can enable logging for the mail() function specifically. It doesn’t record the complete SMTP interaction, but at least function call parameters and invocation script.

ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);

See http://php.net/manual/en/mail.configuration.php for details. (It’s best to enable these options in the php.ini or .user.ini or .htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP’s built-in mail() function is handy and often gets the job done but it has its shortcomings. Fortunately, there are alternatives that offer more power and flexibility including handling a lot of the issues outlined above:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

https://stackoverflow.com/questions/24644436/php-mail-function-doesnt-complete-sending-of-e-mail