D. 777KLM
D. 777KLM

Reputation: 470

Laravel - Creating a Dynamic URL using a Database String

I am with a bit of a stuggle here. I managed to create the dynamic URL using the following code:

Home Page Controller

$satellites = DB::table('satellites')->get();
return view('pages/home', ['satellites' => $satellites]);

Blade File

@foreach($satellites as $satellite)
    <a href="{{$satellite->norad_cat_id}}"><li>{{$satellite->satname}}</li></a>
@endforeach

web.php

Route::get('{norad_cat_id}', 'Satellite@show');

Controller

public function show($norad_cat_id)
{
    return view('pages/satellite');
}

The URL generated is: mysite.com/12345 (where 12345 is the norad_cat_id).

This code manages to create the dynamic URLs using the norad_cat_id from the database - which is what I want. The problem is that I can replace the URL with anything and it still creates a page (ie. replace the 12345 with something not from the database and a page is still created).

What I want is only for a URL to be generated only with the norad_cat_id and if there is no matching norad_cat_id in the database, display a 404 page.

Upvotes: 2

Views: 1800

Answers (4)

Sami Samiuddin
Sami Samiuddin

Reputation: 457

Here's an example using query builder which is what I assume you're using:

public function show($norad_cat_id)
{
    $norad_cat_data = DB::table('satellites')->where('norad_cat_id', $norad_cat_id)->get();

    if (!is_null($norad_cat_id) 
    {
       return view('pages/satellite');
    }
    \App::abort(404);
}

Upvotes: 0

Maraboc
Maraboc

Reputation: 11083

In the show method add a fetch from database if there is no record just abort

public function show($norad_cat_id)
{
    $satellite = DB::table('satellites')->where('norad_cat_id', $norad_cat_id)->first();
    if( ! satellite){
        return abort(404);
    }
    return view('pages/satellite');
}

PS: abort will automatically redirect to your resources/views/errors/404.blade.php

Upvotes: 1

online Thomas
online Thomas

Reputation: 9381

You can do this multiple ways

  1. Create a regex for norad_cat_id

The example shows nummeric ([0-9]+)

Route::get('{norad_cat_id}', 'Satellite@show')->where(['norad_cat_id' => '[0-9]+']);
  1. Use findOrFail() and on fail show the 404.

    try
    {
        $user = Satellites::findOrFail($id);
         return view('norad_cats');
    }
    // catch(Exception $e) catch any exception
    catch(ModelNotFoundException $e)
    {
        return view('404');
    }
    

Upvotes: 1

Tajgeer
Tajgeer

Reputation: 408

You can throw 404 in your controlller (for example). Just check if records exists in database - if not then return error.

Example:

public function show($cat_id)
{
    $sattelites = DB::table('sattelites')->where('norad_cat_id', $cat_id)->get();

    if ($satellites === NULL)
    {
        \App::abort(404);
    }

    return view('pages/sattelite', [
        'satellites' => $satellites
    ]);
}

I think you get the idea.

Upvotes: 0

Related Questions