Pass function variable INSIDE route declaration - laravel

Let's say I have a function in my controller which retrieves users looking something like this:
public function index($category) {
// retrieve users depending on category or all
}
Now is there a way to make named routes to include the function parameter like so:
Route::get('passengers', 'Controller#index(1)')->name('passengers');
Route::get('attendees', 'Controller#index(2)')->name('attendees');
This way they can all use the same function

No you can not pass a parameter the action name, and there is a problem in you routing logic :
Route::get('/{categoryName}', 'Controller#index')->name('index');
And in the controller you will for example get the category by name like this :
public function index($categoryName) {
$category = Category::where('name', $categoryName)->first();
// use $ category as you please ;)
}
In the blade :
route('index', ['categoryName' => $category->name])

If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the URL in their correct positions
https://laravel.com/docs/5.5/routing#named-routes
So, use route() helper like this:
route('passengers', ['category' => 1])
Then you need to add {category} to the route. Also, it's really better to use show() instead of index() here. So, your route will look like this:
Route::get('passengers/{category}', ['as' => 'passengers', 'uses' => 'Controller#show']);

Yes, you can define the param in the url like so:
Route::get('passengers/{yourParam}', 'Controller#index')->name('passengers');
View in docs

Route::get( '{category}', [ 'as' => 'users', 'uses' => 'Controller#index' ]);
Remember to add this route at the end of your routes file in order to not to collide with any other route.
Now in your controller
use Illuminate\Http\Request;
public function index(Request $request)
{
$category = $request->query('category');
// $category will be passengers, attendees, etc
}
Your routes will be
/passengers can be accessed as route('users', ['category' => 'passengers'])
/attendees can be accessed as `route('users', ['category' => 'attendees'])

Related

Router redirecting to the another page

I have route like
Route::get('admin/selfcontacteditdata','SelfcontectController#edit')->name('selfcontectedit');
Route::post('admin/selfcontactupdatedata','SelfcontectController#update')->name('selfcontectupdate');
If i just go to my browser and right admin/selfcontacteditdata it redirect me to
admin/newsshowdata
And my index function is
public function __construct()
{
return $this->middleware('auth');
}
public function index()
{
request()->validate([
'email' => 'required',
'mobileno' => 'required',
'facebook'=>'required',
'google'=>'required',
'map'=>'required',
]);
$data = selfcontect::find(1);
return view('/admin/selfcontectedit',compact('data'));
}
And my middleware is
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
My rest admin routes are working fine.
I had the same problem but I was writing table name wrong and my file was not saved as .blade please check are you also doing the same thing and there is no meaning of validation in edit function your edit function must be like
public function edit()
{
$data = selfcontect::find(1);
return view('/admin/selfcontectedit',compact('data'));
}
and your function name should be edit
You should use Accept key not Content/type
You can't redirect through view, actually your are calling view.
Correct syntax is
return view('view_name',compact('data'));
If you want to redirect to any route you have to call like this
return redirect()->to('admin/selfcontacteditdata');
Redirect to a Route
If in your routes.php file you have a route with a name, you can redirect a user to this particular route, whatever its URL is:
app/Http/routes.php:
get('books', ['as' => 'books_list', 'uses' => 'BooksController#index']);
app/Http/Controllers/SomeController.php
return redirect()->route('books');
This is really useful if in the future you want to change the URL structure – all you would need to change is routes.php (for example, get(‘books’, … to get(‘books_list’, …), and all the redirects would refer to that route and therefore would change automatically.
And you can also use parameters for the routes, if you have any:
app/Http/routes.php:
get('book/{id}', ['as' => 'book_view', 'uses' => 'BooksController#show']);
app/Http/Controllers/SomeController.php
return redirect()->route('book_view', 1);
In case of more parameters – you can use an array:
app/Http/routes.php:
get('book/{category}/{id}', ['as' => 'book_view', 'uses' =>
'BooksController#show']);
app/Http/Controllers/SomeController.php
return redirect()->route('book_view', [513, 1]);
Or you can specify names of the parameters:
return redirect()->route('book_view', ['category'=>513, 'id'=>1]);

Dynamic url routing in Laravel

I am new in Laravel using version 5.8
I do not want to set route manually for every controller.
What i want is that if i give any url for example -
www.example.com/product/product/add/1/2/3
www.example.com/customer/customer/edit/1/2
www.example.com/category/category/view/1
for the above example url i want that url should be treated like
www.example.com/directoryname/controllername/methodname/can have any number of parameter
I have lots of controller in my project so i want this pattern should be automatically identified by route and i do not need to specify manually again and again Directory Name, Controller , method and number of arguments(parameter) in route.
try this:
Route::get('/product/edit/{id}',[
'uses' => 'productController#edit',
'as'=>'product.edit'
]);
Route::get('/products',[
'uses' => 'productController#index',
'as'=>'products'
]);
in the controller:
public function edit($id)
{
$product=Product::find($id);
return view('edit')->with('product',$product);
}
public function index()
{
$products=Product::all();
return view('index')->with('products',$products);
}
in the index view
#foreach($products as $product)
Edit
#endforeach
in the edit view
<p>$product->name</p>
<p>$product->price</p>

How to use multiple method in single route in laravel

I want to use more than one method in a single route using laravel. I'm try this way but when i dd() it's show the plan string.
Route::get('/user',[
'uses' => 'AppController#user',
'as' => 'useraccess',
'roles'=> 'HomeController#useroles',
]);
When i dd() 'roles' option it's show the plan string like this.
"roles" => "HomeController#useroles"
my middleware check the role this way.
$actions=$request->route()->getAction();
$roles=isset($actions['roles'])? $actions['roles'] : null;
The simplest way to accept multiple HTTP methods in a single route is to use the match method, like so:
Route::match(['get', 'post'], '/user', [
'uses' => 'AppController#user',
'as' => 'useraccess',
'roles'=> 'HomeController#useroles',
]);
As for your middleware, to check the HTTP request type, a tidier way would be:
$method = request()->method();
And if you need to check for a specific method:
if (request()->isMethod('post')) {
// do stuff for post methods
}
Here's how you can do multiple methods on a single route:
Route::get('/route', 'RouteController#index');
Route::post('/route', 'RouteController#create');
Route::put('/route', 'RouteController#update');
/* Would be easier to use
* Route::put('/route/{route}', 'RouteController#update');
* Since Laravel gives you the Model of the primary key you've passed
* in to the route.
*/
Route::delete('/route', 'RouteController#destroy');
If you've written your own middleware, you can wrap the routes in a Route::group and apply your middleware to those routes, or individual routes respectively.
Route::middleware(['myMiddleware'])->group(function () {
Route::get('/route', 'RouteController#index');
Route::post('/route', 'RouteController#create');
Route::put('/route', 'RouteController#update');
});
Or
Route::group(['middleware' => 'myMiddleware'], function() {
Route::get('/route', 'RouteController#index');
Route::post('/route', 'RouteController#create');
Route::put('/route', 'RouteController#update');
});
Whichever is easier for you to read.
https://laravel.com/docs/5.6/routing#route-groups

Laravel: Skip some params from route or call Controller#show without adding 'static' adding

Laravel: 5.4
It works, But I want to know if there are other pro-solutions.
I have a route like this
Route::get('{any}-a{id}', function($any, $id) {
return ArticleController::show($id);
})->where(['id' => '[0-9]+', 'any' => '.*']);
But this required public **static** function show($id)
Are there any other solution to call non-static function from Route, or just skip the $any params like ->compact('id') (in Route), or:
Route::get('#something-I-don't-know#-a{id}'), function(**$id**) { ... })?
I want to keep the non-static show function because it come from Route:resource of another Route: route('articles.show',$article->id). I don't want to add the $any param.
Thanks for your time and your answers :D
You could always do this instead of calling static methods:
app()->make('App\Http\Controllers\ArticleController')->show($id);
Full code would be like this:
Route::get('{any}-a{id}', function($any, $id) {
return app()->make('App\Http\Controllers\ArticleController')->show($id);
})->where(['id' => '[0-9]+', 'any' => '.*']);

Laravel - Change URL parameters using GET

I have RESTful API built on Laravel.
Now I'm passing parameter like
http://www.compute.com/api/GetAPI/1/1
but I want to pass parameter like
http://www.compute.com/api/GetAPI?id=1&page_no=1
Is there a way to change Laravel routes/functions to support this?
you can use link_to_route() and link_to_action() methods too.
(source)
link_to_route take three parameters (name, title and parameters). you can use it like following:
link_to_route('api.GetAPI', 'get api', [
'page_no' => $page_no,
'id' => $id
]);
If you want to use an action, link_to_action() is very similar but it uses action name instead of route.
link_to_action('ApiController#getApi', 'get api', [
'page_no' => $page_no,
'id' => $id
]);
href text
with these methods anything after the expected number of parameters is exceeded, the remaining arguments will be added as a query string.
Or you can use traditional concatination like following:
create a route in routes.php
Route::get('api/GetAPI', [
'as' => 'get_api', 'uses' => 'ApiController#getApi'
]);
while using it append query string like this. you can use route method to get url for required method in controller. I prefer action method.
$url = action('ApiController#getApi'). '?id=1&page_no=1';
and in your controller access these variables by following methods.
public function getApi(Request $request) {
if($request->has('page_no')){
$page = $request->input('page_no');
}
// ...your stuff
}
Or by Input Class
public function getApi() {
if(Input::get('page_no')){
$page = Input::get('page_no');
}
// ...your stuff
}
Yes you can use those parameters, then in your controllers you can get their values using the Request object.
public function index(Request $request) {
if($request->has('page_no')){
$page = $request->input('page_no');
}
// ...
}

Resources