Search code examples
laravelroutesslug

modify getRouteKeyName in Laravel 5.7


I defined slug for single DB in a column of structure DB. When I will call the slug in route, Could I get slug from another model (e.g. structure here) in route?

The route is:

localhost:8000/api/singles/firstTest

I defined getRouteKeyName function in Single model:

public function structure()
    {
        return $this->belongsTo(Structure::class);
    }

public function getRouteKeyName()
    {
        return $this->structure()->select('slug')->first();
    }

Solution

  • In your controller you will get the firstTest as route param if you have specified route as :

    Route::get('api/singles/{slug}', 'SomeController@someAction');

    Then controller :

    public function someAction(Request $request, $slug)
    {
        // Perform validations and policy authorization if required
    
        $id = Single::whereHas('structure', function ($query) use($slug) {
            $query->where('slug', '=', $slug);
        })->first();
    
        if(!$id){
            abort(404);
        }
    
        // Process the data using $id obtained above
    }