phplaravel

Display name instead of id in url laravel


I would just like to ask how do I display the name of the business instead of it's id. It's currently displayed like this, localhost:8000/1/Belen'sChoice and desired output is localhost:8000/Belen'sChoice. I can get the name however it says 'trying to find id'.

Controller

 public function show($id)
{
    $categories = Category::all();
    $businesses = Business::find($id);
    if (Auth::check()) {
        $userId = Auth::user()->id;
        $users = User::where('id', $userId)->get();
        $posts = Post::where('business_id', $businesses->id)->get()->sortByDesc('created_at');
        $supporters = Supporter::where('user_id', $userId)->get();
        $photos = Image::where('business_id', $businesses->id)->get();
        $albums = Album::where('business_id', $businesses->id)->get();

        $count = 0;

        if ($businesses->user_id != Auth::user()->id) {
            $businesses->views = $businesses->views + 1;
            $businesses->save();
        } else {
            $businesses->views = $businesses->views;
        }

        return view('businesses.index', [
            'categories' => $categories,
            'businesses' => $businesses,
            'users' => $users,
            'posts' => $posts,
            'supporters' => $supporters,
            'count' => $count,
            'images' => $photos,
            'albums' => $albums,
            ]);
    } else {
        return view('businesses.index', [
        'categories' => $categories,
        'businesses' => $businesses,
        ]);
    }
}

Blade

<a class="text-center" href='{{ url("/businessprofile/".$business->id."/".str_replace(" ", "" ,$business->name)) }}'><img class="bprof-img" src='{{ asset("storage/$business->logo") }}'>{{ $business->name }}</a>

Web.php

Route::get('/businessprofile/{id?}/{name}', 'BusinessController@show');

TIA


Solution

  • take one Column in your business migration

    $table->string('slug')->unique();
    

    and save it like this way in your controller

    //use this at the bottom of your controller
    
        use Illuminate\Support\Str;
                $business = new Business;
                $business->slug = Str::slug($request->name) // whatever you request dring //creating a business row
            //and after that save it
            $business->save();
    

    then in your controller find the row using slug

    public function show($slug)
    {
    $business = Business::where('slug',$slug)->first();
    

    //and rest of your operation }

    href='{{ url("/".str_replace(" ", "" ,$business->slug))}}' then in your web

    Route::get('/{slug}', 'BusinessController@show');