lundi 3 septembre 2018

Laravel 5.6: Trying to access database value from Console\Commands?

So, I'm trying to run a console command and use information from my account table.

First, my models:

User Model

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
...
  public function account()
  {
    return $this->hasOne(Account::class);
  }
}

Account Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{    
  public function user()
  {
    return $this->belongsTo(User::class, 'user_id');
  }
}

UpdateTransfers Command in app/Console/Commands/UpdateTransfers.php

namespace App\Console\Commands;

use App\User;
use App\Account;
use Carbon\Carbon;
use Illuminate\Console\Command;
// use Illuminate\Support\Facades\DB;

class UpdateTransfers extends Command
{
  protected $signature = 'update:transfers {user}';
  protected $description = 'Updating account transfers for a user';

  public function __construct(User $user)
  {
    parent::__construct();

    $this->user = $user;
  }

  public function handle()
  {
    ...
    $nextTransfer = Account::where('user_id', $this->user->id)->first();

    \Log::info($nextTransfer->next_transfer_date);

  }
}

I think there might be an error with my query, alternatively, maybe I'm creating the account record wrong.

Here is one of my listeners for creating a new Account

CreateAccount Listener in app\Listeners\CreateAccount.php

namespace App\Listeners;

use Carbon\Carbon;
use App\Account;
use App\Events\UserRegistered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class CreateAccount
{
/**
 * Create the event listener.
 *
 * @return void
 */
public function __construct()
{
    //
}

public function handle(UserRegistered $event)
{
  $account = new Account();
  $event->user->account()->save($account);

  // here, I'm guessing I actually need something like 
  // $account->user()->save($event->user); this doesn't work though

 }

Second listener in app\Listeners\UpdateUserAccount.php

namespace App\Listeners;

use Artisan;
use Illuminate\Auth\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class UpdateUserAccount
{
/**
 * Create the event listener.
 *
 * @return void
 */
public function __construct()
{
    //
}

/**
 * Handle the event.
 *
 * @param  Login  $event
 * @return void
 */
  public function handle(Login $event)
  {
    // ** This is where I call UpdateTransfers from above
    Artisan::call("update:vc_transfers", ['user' => $event->user]);
  }
}

WHAT I WANT TO DO:

  • User register => create user and then create an account in accounts table
  • Separately, when a user logs in, I want to run the command update:transfers {user}

ERROR

Trying to get property 'next_transfer_date' of non-object



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire