jeudi 4 février 2016

Laravel 5 - Save or update

I want to store a list of departments in my database. I do not create the departments in my system, I obtain them from Active Directory. In the view for departments, I display all the departments. I also have a button to update departments in the database.

This function at the moment looks like the following

public function updateDepartments()
{
    $departments = Helper::returnDepartmentsFromLdap();

    dd($departments);
}

The dd produces something like the following

array:16 [▼
  0  => "Department 1"
  8  => "Department 2"
  21 => "Department 3"
  22 => "Department 4"
  29 => "Department 5"
  43 => "Department 6"
  47 => "Department 7"
  48 => "Department 8"
]

You have to remember though that this list is not being obtained from my database, it is being obtained from Active Directory. However, I now want to add them to my database. So in the same function I do the following

public function updateDepartments()
{
    $departments = Helper::returnDepartmentsFromLdap();

    foreach($departments as $departmentID => $departmentName) {
        $department = new Department();
        $department->departmentID = $departmentID;
        $department->departmentName = $departmentName;
        $department->save();
    }

    return Redirect::route('departments.index')->with('message', 'Departments updated.');
}

Now the problem with the above is that every time the button is pushed, the database will insert new rows. Say I push the button for the first time, my database will be populated with the list. Say I then push it a second time, I do not want the same list added again. If it already exist in the database, it should overwrite it or something. It should only perform a save if a new item is in the list.

Is something like this possible?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire