E
E
Eugene2017-10-07 18:06:56
Laravel
Eugene, 2017-10-07 18:06:56

How to display slug instead of id in URL?

Hello! There are articles, for each of them I formed a slug and wrote it to the database using str_slug(). How to make site.dev/news/slug_url instead of site.dev/news/1. And can it be done without using different packages?
web.php

Route::post('news','[email protected]');
Route::resource('news',"ArticlesController",
    ['except' => ['show']]);
Route::get('news/{slug?}', '[email protected]');

ArticlesController
public function show($id)
    {
        $article = Article::findOrFail($id);
        return view('articles.show', compact('article'));
    }
 public function store(ArticleRequest $request)
    {
        $input = $this->imageArticleRequest($request);
        Auth::user()
            ->articles()
            ->create($input);
        session()->flash('flash_message', 'Статья успешно создана');
        return redirect('news');
    }
 protected function imageArticleRequest($request)
    {
        if ($request->hasFile('article_wall')) {
            $image = $request->file('article_wall');
            $imageName = time() . "." . $image->getClientOriginalExtension();
            $savePath = public_path('/uploads/articleImages/' . $imageName);
            Image::make($image)
                ->save($savePath);
            $input = $request->all();
            $input = array_except($input, 'pathName');
            $input['article_wall'] = $imageName;
            $title = $input['title'];
            $input['slug'] = str_slug($title);
            return $input;
        }
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
UksusoFF, 2017-10-07
@Shelderr

You need to carefully read this section of the documentation: https://laravel.com/docs/5.5/routing
routes/web.php:
Route Service Provider:

public function boot()
{
    parent::boot();

    Route::model('article', App\Article::class);
}

ArticlesController:
public function show(App\Article $article) {
//
}

A
anlamas, 2017-10-07
@anlamas

https://laravel.com/docs/5.5/routing#implicit-binding

public function getRouteKeyName()
{
    return 'slug';
}

Z
Zagoruyko Victor, 2020-03-22
@zacompom

How to make such a link:
Http://domen.ru/slug-category/slug-post.html ???
Can anyone help?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question