Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

php - How rewrite DB::select to model with findOrFail in LARAVEL Controller

Hi i have REGION model but i dont know how rewrite this DB::select. I want it with findOrFail or something for ,,If i find this slug i show page if no i show 404

My web.php route

Route::get('/turnaje/{slug}', [RegionController::class, 'show']);

My Region Controller

public function show($slug)
{

    $regions = DB::select('select * from regions where slug = ?', [$slug]);
    $regions_list = DB::select('select * from regions');

    return view('tournaments.show', [
        'regions' => $regions,
        'regions_list' => $regions_list,
    ]);
}
question from:https://stackoverflow.com/questions/65935464/how-rewrite-dbselect-to-model-with-findorfail-in-laravel-controller

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So you can use the model as a facade and write a similar query. I'm assuming you want an exception thrown when there is no region with that slug?

https://laravel.com/docs/8.x/eloquent#not-found-exceptions

public function show($slug)
{
    $regions = Region::where('slug', $slug)->firstOrFail();
    $regions_list = Region::all();

    return view('tournaments.show', [
        'regions' => $regions,
        'regions_list' => $regions_list,
    ]);
}

You may want to handle the ModelNotFoundException


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...