Skip to content
Advertisement

Laravel Backpack – Set extra attributes before page save

In my PageTemplates.php I have a field like this:

$this->crud->addField([
    'name' => 'adres',
    'label' => 'Adres',
    'type' => 'address',
    'fake' => true,
]);

Now I would like to save also the latitude and longitude of the address they give in (if it can be found). I’ve copied the PageCrudController and changed the config in config/backpack/pagemanager.php to:

return [
    'admin_controller_class' => 'AppHttpControllersAdminPageCrudController',
    'page_model_class'       => 'AppModelsPage',
];

In my store function I have:

public function store(StoreRequest $request)
{
    $address = $request->request->get('adres');
    $addressObj = app('geocoder')->geocode($address)->get()->first();

    if($addressObj)
    {

    }

    $this->addDefaultPageFields(Request::input('template'));
    $this->useTemplate(Request::input('template'));

    return parent::storeCrud();
}

But what do I place in the if statement? How can I add (= set) an extra field to the extras field in my database?

Advertisement

Answer

Fixed it by doing the following:

Add latitude and longitude as hidden fields:

$this->crud->addField([
    'name' => 'latitude',
    'type' => 'hidden',
    'fake' => true,
]);

$this->crud->addField([
    'name' => 'longitude',
    'type' => 'hidden',
    'fake' => true,
]);

Set attributes by doing the following:

if($addressObj)
    {
        $request['latitude'] = $addressObj->getCoordinates()->getLatitude();
        $request['longitude'] = $addressObj->getCoordinates()->getLongitude();
    }
}

Change parent::updateCrud to parent::updateCrud($request);.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement