How to display a message in console using a seeder class in Laravel 5.8?
Asked Answered
Y

3

7

To display an error while using Laravel Artisan the official Laravel 5.8 documentation says:

$this->error('Something went wrong!');

But what's the context of $this?

Following is the contents of the seeder class file:

use Illuminate\Database\Seeder;

class PopulateMyTable extends Seeder
{
    public function run()
    {
        $this->info("Console should show this message");
    }
}
Yawp answered 12/9, 2019 at 20:32 Comment(1)
@porloscerrosΨ Got it, but how? Do I need to wrap about in Artisan::command?Yawp
E
16

You can do it by $this->command->method().

Where $this is this Seeder instance, command is this seeder console Command instance,
and method() could be any of the command available output methods.

<?php

use Illuminate\Database\Seeder;

use App\User;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $message = 'sample ';
        $this->command->info($message . 'info');
        $this->command->line($message . 'line');
        $this->command->comment($message . 'comment');
        $this->command->question($message . 'question');
        $this->command->error($message . 'error');
        $this->command->warn($message . 'warn');
        $this->command->alert($message . 'alert');
    }
}

Eduino answered 12/9, 2019 at 22:24 Comment(1)
How to save this post?Parliamentarianism
B
0

Now, the $command is defined as protected and it is not accessible through the seeders.

May a just PHP echo do the trick.

Brown answered 21/8, 2024 at 15:31 Comment(0)
G
0

Laravel 11 update:

In seeders, you can access the output components using:

$this->command->outputComponents()->info('info message');
$this->command->outputComponents()->success('success message');
$this->command->outputComponents()->error('error message');
Glissando answered 22/8, 2024 at 7:41 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.