kevinabraham kevinabraham - 1 year ago 94
PHP Question

How to log errors in try/catch statement laravel?

Im performing a try catch statement where I need the code to do something and if it fails catch the error, log it to the laravel log file and continue with the loop. My code is:

foreach ($logins as $login) {
try {
// Do something here
} catch (Exception $e) {
// Log errors
\Log::error( $e->getMessage() );

But I am getting an error that reads

Namespace declaration statement has to be the very first statement in the script

I've used \Log:: in the name space and also tried adding the
use Log;
but I still get this error.

Answer Source

In one of the scripts, there is a namespace declaration similar to this:

namespace projects\name;

The error is triggered because there is some other script line before the declaration. That's illegal: namespace declaration must be the first execution statement.

Once you fix that, then this line:


Will also cause you an error. A leading \ means that you're accessing a class in the global PHP namespace. If your Log class is in a specific namespace, for example projects\name, then you can use the class in one of two ways. Using a fully qualified name:


Or using a use statement.

use projects\name\Log; //early in the file. No need for leading \
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download