Automatically generate routes with laravel

0

Well I have a database that contains some tables, which are:

  

-Category.

     

-Subcategories.

What I want to do is that if I add a new category, I do not have to place a new route, but it will be automatically generated by the database, that is, if I place a new category called Autos, then it will be create a route that calls mipagina.com/Categories/autos

I do not know if I made myself understood

    
asked by Yeferson Mejias 22.01.2018 в 15:08
source

1 answer

1

In itself, they are not generated automatically. you would have to generate a global route for all your products, but instead of how you usually access it through the id , you can access a field slug or url in your table. you must add a field in your table for example url

In your model Categoria , in your mutador at the time you add the name, assign the field url by calling the function str_slug () to generate a% friendly% co

 /**
 * Mutator for name attribute.
 *
 * @return void
 */
public function setNameAttribute($value)
{
    $this->attributes['name'] = ucwords($value);
    // asignamos el campo url con nombre
    $this->attributes['url'] = str_slug($value);
}

On your routes

Route::get('categorias/{categoria}', 
        'CategoriaContoller@categoriaunica')->name('categoriaunica');

In your controller you might have something like this, for example to recover the URL , (this method can be improved)

public function categoriaunica($categoria)
{
    $categoria = Categoria::where('url','=',$categoria)->first();
    $subcategorias = SubCategoria::where('categoria' ,'=',$categoria->id)->get();
    return view('subcatexcategoria',compact('subcategorias','categoria'));
}
    
answered by 22.01.2018 / 15:40
source