How to set a route parameter default value from request url in laravel - laravel

I have this routing settings:
Route::prefix('admin/{storeId}')->group(function ($storeId) {
Route::get('/', 'DashboardController#index');
Route::get('/products', 'ProductsController#index');
Route::get('/orders', 'OrdersController#index');
});
so if I am generating a url using the 'action' helper, then I don't have to provide the storeId explictly.
{{ action('DashboardController#index') }}
I want storeId to be set automatically from the request URL if provided.
maybe something like this.
Route::prefix('admin/{storeId}')->group(function ($storeId) {
Route::get('/', 'DashboardController#index');
Route::get('/products', 'ProductsController#index');
Route::get('/orders', 'OrdersController#index');
})->defaults('storeId', $request->storeId);

The docs mention default parameter though in regards to the route helper (should work with all the url generating helpers):
"So, you may use the URL::defaults method to define a default value for this parameter that will always be applied during the current request. You may wish to call this method from a route middleware so that you have access to the current request"
"Once the default value for the ... parameter has been set, you are no longer required to pass its value when generating URLs via the route helper."
Laravel 5.6 Docs - Url Generation - Default Values

In my Laravel 9 project I am doing it like this:
web.php
Route::get('/world', [NewsController::class, 'section'])->defaults('category', "world");
NewsController.php
public function section($category){}

Laravel works exactly in the way you described.
You can access storeId in your controller method
class DashboardController extends Controller {
public function index($storeId) {
dd($storeId);
}
}
http://localhost/admin/20 will print "20"

Related

Custom Routes not working - 404 not found

I'm trying to create a custom route. The must be in this format: http://localhost:8000/home-back-to-school but instead I get a 404 not found error. http://localhost:8000/posts/home-back-to-school works, but that's not what I'm trying to get working.
My routes on web.php are defined as: Route::resource('posts',PostsController::class);
I modified the Route Service Provider by adding the code below:
parent::boot();
Route::bind('post',function($slug){
return Post::published()->where('slug',$slug)->first();
});
The published scope is defined in the Post Model file(Post.php) as:
public function scopePublished()
{
return $this->where('published_at','<=',today())->orderBy('published_at', 'desc');
}
I've done previously with laravel 5.x, now struggling with laravel 8.x
Link to the Documentation: Laravel 8 Documentation
You should define a custom route since you don't want to use the resourceful route for this method.
In your web.php
// Keep all your resource routes except the 'show' route since you want to customize it
Route::resource('posts', PostsController::class)->except(['show']);
// Define a custom route for the show controller method
Route::get('{slug}', PostsController::class)->name('posts.show');
In your PostController:
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
In your Post model:
// Tell Laravel your model key isn't the default ID anymore since you want to use the slug
public function getRouteKeyName()
{
return 'slug';
}
You may have to fix your other Post routes to make them work with this change since you are now using $post->slug instead of $post->id as the model key.
Read more about customizing the model key:
https://laravel.com/docs/8.x/routing#customizing-the-default-key-name
You should also remove the code you have in the boot method and use the controller instead.
Finally, make sure your post slug is always unique for obvious reason.
Note:
You may run into problems if your other routes are not related to the Post model.
Imagine if you have a route called example.com/contact-us. Laravel has no way to "guess" if this route should be sent to the PostController or the ContactController. contact-us could be a Post slug or it could be a static route to your contact page. That's why it's generally a good idea to start your urls with the model name. In your case, it would be a good idea for your Post route to start with "/posts/" like this: http://example.com/posts/your-post-slug. Otherwise you may run into all sorts unexpected routing issues.
Don't fight the framework: Always follow best practices and naming conventions when you can.

Laravel 5.7 ApiResource GET params empty

I use Laravel 5.7 for my JSON API web application.
In my routes/api.php file, I created the following route :
Route::apiResource('my_resource', 'API\Resource')->except(['delete']);
I added the corresponding controller and methods (index, show,...) and everythink work perfectly. My issue is the following : I would like to add optional GET params like this :
http://a.x.y.z/my_resource?param=hello&param2=...
And for instance being able to retrieve 'hello' in my index() method. However, when I print the value of $request->input('param'), it's empty. I just don't get anything.
Yet, if I create a route like this, with an optional parameter:
Route::get('/my_resource/{param?}', 'API\Resource');
I'm able to get the parameter value in my controller method.
Here is my index method :
class Resource extends Controller {
public function index(Request $request)
{
print($request->input('param'));
// ...
}
// ...
}
Am I missing something ? I'm still new in Laravel maybe I missed something in the documentation.
Thanking you in advance,
You can use:
$request->route("param");

How can I implement Resource Controllers if I use many "get" on the laravel?

I have routes laravel like this :
Route::prefix('member')->middleware('auth')->group(function(){
Route::prefix('purchase')->group(function(){
Route::get('/', 'Member\PurchaseController#index')->name('member.purchase.index');
Route::get('order', 'Member\PurchaseController#order')->name('member.purchase.order');
Route::get('transaction', 'Member\PurchaseController#transaction')->name('member.purchase.transaction');
});
});
My controller like this :
<?php
...
class PurchaseController extends Controller
{
...
public function index()
{
...
}
public function order()
{
...
}
public function transaction()
{
...
}
}
I want to change it to Resource Controllers(https://laravel.com/docs/5.6/controllers#resource-controllers)
So I only use 1 routes
From my case, my routes to be like this :
Route::prefix('member')->middleware('auth')->group(function(){
Route::resource('purchase', 'Member\PurchaseController');
});
If I using resouce controller, I only can data in the index method or show method
How can I get data in order method and transaction method?
You could try like this, Just put your resource controller custom method up resource route.
Route::prefix('member')->middleware('auth')->group(function(){
Route::get('order', 'Member\PurchaseController#order')->name('member.purchase.order');
Route::get('transaction', 'Member\PurchaseController#transaction')->name('member.purchase.transaction')
Route::resource('purchase', 'Member\PurchaseController');
});
For the resource controller, it is pre-defined by the Laravel, which contain only the 7 method.
Shown at below table.
So, if you want any other method, you have to definde by youself.
php artisan route:list
You can use this to check all the route you defined.
The other answers on here are pretty much correct.
From my other answer you linked this question in from, here that way based on what MD Iyasin Arafat has suggested, if you are using laravel 5.5+:
# Group all routes requiring middleware auth, thus declared only once
Route::middleware('auth')->group(function(){
# Suffix rules in group for prefix,namespace & name with "member"
Route::namespace('Member')->prefix('member')->name('member.')->group(function () {
Route::get('purchase/order', 'PurchaseController#order')->name('purchase.order');
Route::get('purchase/transaction', 'PurchaseController#transaction')->name('purchase.transaction');
Route::resource('purchase', 'PurchaseController');
});
});
Grouping Methods ( ->group() ) :
Controller Namespace ( ->namespace('Member') )
Prepends to 'PurchaseController' to give
'Member\PurchaseController'
Route Name (->name('member.'))
Prepends to name('purchase.order') to give
route('member.purchase.order')
URI Request (->prefix('member'))
Prepends to /purchase to give example.com/member/purchase
As you can see, using the methods above with group() reduces repetition of prefix declarations.
Hint
Custom routes must always be declared before a resource never after!
Example to use if you have a lot of custom routes for Purchase Controller and how a second controller looks for member group:
# Group all routes requiring middleware auth, thus declared only once
Route::middleware('auth')->group(function(){
# Suffix rules in group for prefix,namespace & name with "member"
Route::namespace('Member')->prefix('member')->name('member.')->group(function () {
Route::prefix('purchase')->name('purchase.')->group(function() {
Route::get('order', 'PurchaseController#order')->name('order');
Route::get('transaction', 'PurchaseController#transaction')->name('transaction');
Route::get('history', 'PurchaseController#history')->name('history');
Route::get('returns', 'PurchaseController#returns')->name('returns');
Route::get('status', 'PurchaseController#status')->name('status');
Route::resource('/', 'PurchaseController');
});
Route::prefix('account')->name('account.')->group(function() {
Route::get('notifications', 'AccountController#notifications')->name('notifications');
Route::resource('/', 'AccountController');
});
});
});

Call to a member function middleware() on null

I use the following middleware in routing Laravel:
Route::group(['prefix' => 'api/'], function() {
Route::resource('admin', 'adminController')->middleware('auth');
Route::resource('profile', 'profileController')->middleware('role');
});
I get this error when i call 'admin' or 'profile' path in URL
Use this
Route::prefix("/dashboard")->middleware(['first','second'])->group(function(){
});
It is because Route::resource() does not return anything. Its void. It doesn't return an object.
Laravel 5.4 - Illuminate\Routing\Router#resource
In Laravel 5.5 (in development), Route::resource() will be returning an object for fluently adding options to.
Simply reverse the order:
Route::middleware('scope:clock-in')->resource('clock', 'ClockController');
As lagbox stated:
Route::resource() does not return anything.
However middleware does.
Most likely your resource controller is not resolving to an actual controller. Some things to check
Check you actually have an adminController, and that the class name is in the correct case
Check that your controller is in the default namespace and, if not, change the controller namespace, or add a namespace attribute to your route
Check that your controller is not causing an exception on start that is being ignored resulting in you having a null controller.
In Laravel 8.x you can solve this problem with:
Route::group(['middleware' => 'auth','middleware' => 'role'], function () {
..........
});

Laravel form open with multiple parameters

I am trying to pass variables with form open with following code:
{{ Form::open(['method' => 'PATCH','route' => ['note.update','project','1','1']]) }}
Here is my NoteController.php file
Class NoteController extends BaseController{
public function update($belongs_to,$unique_id=0,$note_id=0){
return $unique_id;
}
}
routes.php file is
Route::resource('note', 'NoteController');
Why I am only able to access $belongs_to variable and $unique_id and $note_Id are always 0 as given as default value??
That's because the routes registered with Route::resource only take one url parameter.
Take a look a this
So what you need to do is use this route:
Route::patch('note/{belongs_to}/{unique_id?}/{note_id?}', 'NoteController#update');
If you want to keep the other routes from Route::resource just add it before Route::resource
Route::patch('note/{belongs_to}/{unique_id?}/{note_id?}', 'NoteController#update');
Route::resource('note', 'NoteController');
If you don't want to add the route like this, you'll have to use query parameters to pass additional information

Resources