I am trying to fetch a row from a second database using a custom artisan command in Laravel. Now i want to print the result of the query but I keep getting an error. I would appreciate any help.
I setup the connection to two databases and they are connected and running without problems. the table that I am working with is called person and contains multiple columns such as name, surname, person_id (which is auto increment and primary key) and ssn. I also created a custom artisan command that fetches a row from the database when using
php artisan import-users:DB 12345678
and the query
DB::connection('mysql2')->select('SELECT * FROM person WHERE ssn=?', [$ssn])
the result of the query is placed in the variable $user and now i just want to print it out but i keep getting errors. here is what i tried
$name = $user['name'];
which gives the
ErrorException : Undefined index: name
$this->line($user[0]);
which gives the
ErrorException : Object of class stdClass could not be converted to string
$this->line($user->name);
which give the
ErrorException : Trying to get property 'name' of non-object
I also tried many things but nothing worked. Thanks again
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class ImportUsers extends Command{
protected $signature = 'import-users:DB {ssn}';
protected $description = 'import users from old database';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$ssn = $this->argument('ssn');
$user = DB::connection('mysql2')->select('SELECT * FROM person WHERE
ssn=?', [$ssn]);
$this->line($user->name);
$this->info($ssn.' Done');
}
}
used like that
for signle row
public function handle()
{
$ssn = $this->argument('ssn');
$user = DB::connection('mysql2')->select('SELECT * FROM person WHERE
ssn=? limit 1', [$ssn]);
if(isset($user[0])){
$this->line($user[0]->name);
}
$this->info($ssn.' Done');
$this->table($headers, $newUsers);
}
for multiple rows(array)
public function handle()
{
$ssn = $this->argument('ssn');
$user = DB::connection('mysql2')->select('SELECT * FROM person WHERE
ssn=?', [$ssn]);
//$userNameArray = []; //if you want to show name in table
if(count($user) > 0) {
foreach($user as $item) {
$this->line($item->name);
//$userNameArray[] = $item->name;
}
}
$this->info($ssn.' Done');
//$this->table(['Name'],$userNameArray); //optionall
}