Last active
March 26, 2019 18:02
-
-
Save ahurov/49057f86292defac7f32f4c0592a2c95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Observers; | |
| use Illuminate\Database\Eloquent\Model; | |
| class RedirectObserver | |
| { | |
| const REDIRECTS = [ | |
| \Modules\Shop\Entities\Product::class => [ | |
| 'route' => 'product', | |
| 'properties' => ['domain','slug'], | |
| 'check' => 'slug', | |
| ], | |
| ]; | |
| public function updating(Model $model) | |
| { | |
| $redirectData = null; | |
| foreach(self::REDIRECTS as $className => $redirect) { | |
| if(is_a($model, $className)) { | |
| $redirectData = $redirect; | |
| break; | |
| } | |
| } | |
| if(!$redirectData) return; | |
| $old = $model->getOriginal($redirectData['check']); | |
| $new = $model->{$redirectData['check']}; | |
| if($old === $new) return; | |
| Redirect::create([ | |
| 'from' => $this->createUrl($redirectData['route'], $model, $redirectData['properties'], true), | |
| 'to' => $this->createUrl($redirectData['route'], $model, $redirectData['properties']), | |
| ]); | |
| } | |
| private function createUrl($route, $model, $propertiesNames, $old=false) | |
| { | |
| $properties = []; | |
| foreach ($propertiesNames as $key => $propertyName) { | |
| $properties[$propertyName] = $old ? $model->getOriginal($propertyName) : $model->{$propertyName}; | |
| } | |
| return route($route, $properties); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment