A
A
Andrew2014-11-06 14:25:20
Laravel
Andrew, 2014-11-06 14:25:20

Laravel. How to change primaryKey in query to model?

There is a page table
BUtJPuU.png
There is a Page class

<?php
class Page extends Eloquent 
{

}

There is a route for displaying a page by id
Route::model('page', 'Page');
Route::get('/pagebyid/{page}', function(Page $page)
{
  print_r($page);
});

Everything is working. But how now to make another route fetching the page by url work?
Route::model('url', 'Page');
Route::get('/pagebyurl/{url}', function(Page $url)
{
  print_r($url);
});

The selection still goes by id.
In theory, you can change the primaryKey in the Page. But then the /pagebyid/1 route will stop working. You can also correct the query in the route with handles
protected $primaryKey = 'url';
Route::get('/pagebyurl/{url}', function($url) 
{
  $page = Page::where('url', $url)->get();
  print_r($page);
});

But here we are already collecting the query through where, but I want to do everything through the smart Route::model()
Actually the question. How to get the page by url field in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gladkovskiy, 2014-11-06
@SMGladkovskiy

Defining routes with Route::model() is good to use when you have a fully CRUD application. Let's say, if a fairly simple API for something or a resource is sharpened to work with data such as directories. Otherwise, I highly recommend splitting the routes. Since it will always be possible to find the desired route and fix it (debugging / support will not be such a headache), you can always see and manage the types of requests (work on code development will be simplified), and if any changes are made to this method, then do not there will be problems with reworking the code (simplifying and improving compatibility). Plus, if you put the logic in a separate application layer, it will also be easier to develop and maintain...
All this applies to Route::controller().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question