I have the following route:
Route::get('news', [
'as' => 'news',
'uses' => 'ArticleController#getIndex',
]);
There are also other routes that use the same resource controller, e.g:
Route::get('travel', [
'as' => 'travel',
'uses' => 'ArticleController#getIndex',
]);
In the article controller, how can I get the category of the articles. e.g. travel or news?
I can't turn it into a route param e.g.
Route::get('{travel}', [
'as' => 'travel',
'uses' => 'ArticleController#getIndex',
]);
As there are other sections such as contact, faqs, etc that do not use the article controller.
I know I could put it all on one route:
Route::get('/article/{category}', [
'as' => 'travel',
'uses' => 'ArticleController#getIndex',
]);
But I want pretty URLS like:
mydomain.com/category-slug/article-slug
Ideally if I could use a resource controller:
Route::resource('news', ArticleController');
With some sort of array:
Route::resource(['news', 'travel'], ArticleController');
So my questions:
How can I get the name of the resource. e.g. news, travel in my controller?
Is there an easy way to specify varying routes to the same resource?
For Example Keep your routes like this as your static routes will be limited and need to be unique so they will not get conflict between routes
demo routes :
Route::get('contact', [
'as' => 'contact',
'uses' => 'contactController#getIndex',
]);
Route::get('{travel}', [
'as' => 'travel',
'uses' => 'ArticleController#getIndex',
]);
In order to achieve a route like that:
mydomain.com/category-slug/article-slug
Use the following:
Route::get('/{category}/{article}', 'ArticleController#getArticle');
Then in your controller, you will have 2 parameters in your getArticle method.
public function getArticle($category, $article)
{
//Your code here
}
In order to have pretty urls you need to make a few steps:
1)
First of all you need to add a column to your articles table called for example 'slug'.
2) Then you need to specify your route key in your article model. Like this:
Article model
public function getRouteKeyName()
{
return 'slug';
}
3) When you add an article you should create the slug by your own in order to be unique. so in your controller that you create the article add this code.
$slug = str_slug($article['title'], '-');
$slugs_count = DB::table('articles')->where('name',$article['title'])- >count();
if($slugs_count>1){
$slug = $slug.'-'.($slugs_count-1);
}
$article->slug = $slug;
$article->update();
4) Now we have to set the route
Route::get('/article/{slug}', [
'as' => 'travel',
'uses' => 'ArticleController#getIndex'
])->where(['slug','[\w\d\-\_]+']);
5) Finally in order to get the article you need
$article = Article::where('slug','=',$slug)->first();
If you want to use categories etc you could pass more parameters in your route and manipulate it in your controller. like this
Route::get('/article/{category}/{slug}', [
'as' => 'travel',
'uses' => 'ArticleController#getIndex'
])->where(['slug','[\w\d\-\_]+','category','[\w\d\-\_]+']);
The where clause is to restrict the parameter with some regular expressions(its optional).
I forgot to mention that the routekeyname in your model works in laravel 5.2.
Related
I am using apiResource and other routes. I grouped them like below:
Route::group(['prefix' => 'posts'], function () {
Route::group(['prefix' => '/{post}'], function () {
Route::put('lablabla', [PostController::class, 'lablabla']);
});
Route::apiResource('/', PostController::class, [
'names' => [
'store' => 'create_post',
'update' => 'edit_post',
]
]);
});
all apiResource routes except index and store do not work! How should I group routes?
Your syntax for routing is wrong,
Notes
You will provide a uri for the apiResource (plural)
eg. Route::apiResource('posts', PostController::class);
Your name of resource route is wrong
Get this out https://laravel.com/docs/8.x/controllers#restful-naming-resource-routes
it should be
Route::apiResource('posts', PostController::class)->names([
'store' => 'create_post',
'update' => 'edit_post',
]);
No need of repeating Route::group, you can just write your routes like this
Route::prefix('posts')->group(function () {
Route::put('lablabla', [PostController::class, 'lablabla']);
});
Route::apiResource('posts', PostController::class)->names([
'store' => 'create_post',
'update' => 'edit_post',
]);
Your syntax is incorrect, there is a names method. See the documentation here https://laravel.com/docs/8.x/controllers#restful-naming-resource-routes.
Bizarre issue, lets see some routes:
Route::get('/admin/races', ['as' => 'races.list', 'uses' => 'RacesController#index']);
Route::get('/admin/races/{race}', ['as' => 'races.race', 'uses' => 'RacesController#show']);
Route::get('/admin/races/create', ['as' => 'races.create', 'uses' => 'RacesController#create']);
Route::get('/admin/races/{race}/edit', ['as' => 'races.edit', 'uses' => 'RacesController#edit']);
Seems normal enough, lets see the controller:
class RacesController extends Controller {
public function index() {
return view('admin.races.list');
}
public function show(GameRace $race) {
return view('admin.races.race', [
'race' => $race,
]);
}
public function create() {
return view('admin.races.manage', [
'race' => null,
]);
}
public function edit(GameRace $race) {
return view('admin.races.manage', [
'race' => $race,
]);
}
}
Seems normal enough. The issue is:
When I go to /admin/races/create I get a 404. The reason being is because, exception:
Illuminate\Database\Eloquent\ModelNotFoundException^ {#851
#model: "App\Flare\Models\GameRace"
#ids: array:1 [
0 => "create"
]
#message: "No query results for model [App\Flare\Models\GameRace] new"
#code: 0
#file: "./vendor/laravel/framework/src/Illuminate/Routing/ImplicitRouteBinding.php"
#line: 47
trace: {
.....
Why is calling:
<li>Create Race</li>
Causing Laravel to take the word create and inject it in as a model? No other route that I have, that is similar does this. For context, here's how we create items:
Route::get('/admin/items/create', ['as' => 'items.create', 'uses' => 'ItemsController#create']);
Same concept, just instead of races its items. So how laravel messing this up?
I have run all the cache clears and route clears and everything. Same issue. Even tests are failing on this. No where am I calling this with a param (especially not one called create) so it should not be assuming there is a param.
It's because you have defined Route::get('/admin/races/{race}' .. first, so it'll hit that route regardless of what the value is. Simply moving the create route before the show route will solve your problem.
Route::get('/admin/races', ['as' => 'races.list', 'uses' => 'RacesController#index']);
Route::get('/admin/races/create', ['as' => 'races.create', 'uses' => 'RacesController#create']);
Route::get('/admin/races/{race}', ['as' => 'races.race', 'uses' => 'RacesController#show']);
Route::get('/admin/races/{race}/edit', ['as' => 'races.edit', 'uses' => 'RacesController#edit']);
That said, you can simplify this a lot more with a simple resource-route.
Route::resource('/admin/races', ['as' => 'races.list', 'uses' => 'RacesController'])->only("index", "show", "create", "edit");
An alternative solution to the accepted answer is to specify conditions for the parameter in the parametrised route. For example if {race} needs to be numeric you can do:
Route::get('/admin/races', ['as' => 'races.list', 'uses' => 'RacesController#index']);
Route::get('/admin/races/{race}', ['as' => 'races.race', 'uses' => 'RacesController#show'])->where('race', '\d+');
Route::get('/admin/races/create', ['as' => 'races.create', 'uses' => 'RacesController#create']);
Route::get('/admin/races/{race}/edit', ['as' => 'races.edit', 'uses' => 'RacesController#edit']);
This is useful in the cases where you can't control the order of the routes (e.g. there's a package registering routes that conflict).
In the example from the tutorial, it shows up.
Route::group([
'prefix' => 'admin',
'as' => 'admin.'
], function () {}
Can someone tells me what 'as' does? Also, is the dot next to the 'admin' neccessary?
Thank you.
Let's say, for example, that you have this route:
Route::get('admin', [
'as' => 'admin', 'uses' => 'AdminController#index'
]);
By using as you assign custom name to your route. So now, Laravel will allow you to reference said route by using:
$route = route('admin');
So you don't have to build the URL manually over and over again in your code. You don't really need . notation if you only want to call your route admin. If you want a more detailed name of your route, lets say for ex. admin product route, then you use the . notation, like this:
Route::get('admin/product', [
'as' => 'admin.product', 'uses' => 'AdminController#showProduct'
]);
So now, you will be able to call this route by the assigned name:
$route = route('admin.product');
Update:
The previous answer I provided is valid for a single routes. For the route groups, the procedure is very similar. In the route groups you need the . notation when you add a custom name, since you will be referencing another route after that . notation. This will allow you to set a common route name prefix for all routes within the group. So by your example, lets say you have a dashboard route inside your admin route group:
Route::group(['as' => 'admin.'], function () {
Route::get('dashboard', ['as' => 'dashboard', function () {
//Some logic
}]);
});
Now, you will be able to call the dashboard route like this:
$route = route(admin.dashboard);
You can read more about this in Laravel official documentation.
you may specify an as keyword in the route group attribute array, allowing you to set a common route name prefix for all routes within the group.
For Example
Route::group(['as' => 'admin::'], function () {
// Route named "admin::"
});
UseRoute Name like {{route(admin::)}} or route('admin::')
you can use an 'as' as a named route. if you do not prefix your route name in group route than you may add custom route name like this.
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'roles'], 'roles' => ['2']], function () {
Route::post('/changeProfile', ['uses' => 'UserController#changeProfile',
'as' => 'changeProfile']);
});
I need check domain for some routes. Then after check, I need redirect domain https://two.com to https://one.com with middleware in laravel.
For example:
Routes:
Route::get('/', ['as' => 'index', 'uses' => 'IndexController#index']);
Route::get('termsAndCondition', ['as' => 'termsAndCondition', 'uses' => 'IndexController#termsAndCondition']);
Route::get('aboutUs', ['as' => 'aboutUs', 'uses' => 'IndexController#aboutUs']);
Route::get('privacy', ['as' => 'privacy', 'uses' => 'IndexController#privacy']);
I need check aboutUs and privacy for domain name.
If domain name is https://two.com/aboutUs or https://two.com/privacy redirect to https://one.com/aboutUs or https://one.com/privacy.
I need check with middleware.
Thanks.
You can do something like this in a middleware:
if (request()->getHttpHost() === 'two.com' && in_array(request()->path(), ['aboutUs', 'privacy'])) {
return redirect('https://one.com/' . request()->path());
}
you can check url segments using segment() helper something like:
if(Request::segment(1)==='aboutus')
{
return redirect(route('your other route');
}
if(Request::segment(1)==='privacy')
{
return redirect(route('your other route');
}
You can add that check in your middleware, segment() expects an integer param like in case above 1 will check first wildcard after domain name.
i have in my controller
public function details($id)
{
$claim = Claim::findOrFail($id);
$details = $claim->details;
return response()->json([], 200);
}
and I have in my routes
Route::resource('claims', 'Admin\\ClaimsController',['names'=> ['details'=>'admin.claims.details'], 'only' => ['index','store','update','destroy','details']]);
when I run php artisan route:list i do not see the admin.claims.details( admin/claims/1/details) in the list
the documentation is pretty vague here so I'm asking how to properly set a custom route? How do I specify if its "POST" or "GET"?
To override the default resource controller actions' route names, you can pass a names array with your options.
For example:
Route::resource('claims', 'ControllerClassName', [
'names' => [
'index' => 'admin.claims.details',
'create' => 'admin.claims.create',
// etc...
],
'only' => [
'index','store','update','destroy','details'
]
]);
REF: https://laravel.com/docs/5.2/controllers#restful-naming-resource-routes
Here are examples of setting custom named get/post routes.
GET Route
Route::get('claims', ['as' => 'admin.claims.details', uses => 'ControllerClassName']);
POST Route
Route::post('claims', ['as' => 'admin.claims.details', uses => 'ControllerClassName']);
REF: https://laravel.com/docs/5.2/routing#named-routes