Appearance
How do I write to the console from a Laravel Controller?
You can use the Log facade to write to a log file from a Laravel controller. Note that standard HTTP controllers run in a web context, so they cannot write directly to a terminal console. For debugging, use dd() or dump() to output data to your browser's developer tools or CLI. Here's an example:
How to write to a log file and debug output in a Laravel Controller?
php
<?php
use Illuminate\Support\Facades\Log;
class MyController extends Controller
{
public function index()
{
Log::info('This is some useful information.');
dump('Debugging data');
// dd('Debugging data'); // Stops execution after output
return view('welcome');
}
}This will write the message 'This is some useful information.' to the log file when the index method is called. The dump() call outputs the debugging data to your browser's console or CLI.
By default, the message is written to storage/logs/laravel.log. You can customize the log channel and file path in config/logging.php. For example, to use a specific channel directly in your code:
php
Log::channel('daily')->info('This goes to the daily log file.');If you specifically need console output (e.g., when running the controller via an Artisan command or for debugging), use dd() or dump() instead of echo or print_r. These functions provide structured output and are better suited for modern Laravel debugging workflows.