Search code examples
phpjsonlaravelrestlaravel-artisan

Artisan migration won't run in controller


I have a DB of contacts which is populated via API /users, it works correctly collecting all users data into table.

I want the user to hit a button and get an updated contact list with unique value (phone and email)

To do this I wish to run a migrate:refresh whenever the user hits the #getcontacts button, so it gets a brand new list of contacts updated to the latest insert.

I still get


SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry for key 'contacts_email_unique'

use Artisan

[...]



public function makeContacts(){

    $apiResponse = file_get_contents($this->userList); //call to the api URL

    $users = json_decode(
        $this->extractString($apiResponse,9,-1)
    ); //hard formatting response for my own purposes 

 Artisan::call('migrate:refresh', array('--path' => 'app/migrations', '--force' => true));

    foreach ($users as $user){ 

        $contact = new Contact(); 
        $contact->firstname = $user->firstname; 
        $contact->lastname = $user->lastname; 
        $contact->email = $user->email; 
        $contact->phone = $user->phone; 
        foreach ($user->zones->zones as $zone){
            $contact->zone = $zone->name;
        }
        $contact->save(); 

    }
}

I noticed that:

  1. calling it at the very beginning of my function doesn't change anything
  2. refresh command works perfectly if called from console
  3. dumping result gives 0 (I don't know what does it means, actually)

What can I do to get rid of this problem? Where is my mistake? I can't really understand why it won't run the command. Syntax seems to be correct tho, thanks for the help!!


Solution

  • Thanks to lewis4u: https://stackoverflow.com/users/2502731/lewis4u

    I used an empty array as second parameter of Artisan:call function and it works perfectly now.