I want to use a argument in a create action, but when I try to access the action:
Missing argument 1 for App\Http\Controllers\AdsDiagController::create()
Here is the create action:
public function create($id){
$record = TestRecord::findOrFail($id);
return view("adsdiag.create", ["record" => $record]);
}
Here is the link to the action:
Create
And the route:
Route::resource('adsdiag', 'AdsDiagController');
I'm newbie in laravel, and I'm really confused with routes. I appreciate any help.
To solve your problem you should use in your route.php
Route::get('adsdiag/{id}/',AdsDiagController#create);
Reason
When you call Route::resource('adsdiag', 'AdsDiagController') it generates these routes
Route::get('adsdiag','AdsDiagController#index');
Route::post('adsdiag','AdsDiagController#store');
Route::get('adsdiag/create','AdsDiagController#create'); // you can see that create method doesn't have any arguments here.
Route::get('adsdiag/show/{id}','AdsDiagController#show');
Route::post('adsdiag/update','AdsDiagController#update');
Route::get('adsdiag/edit/{id}','AdsDiagController#edit');
Route::delete('adsdiag/destroy/{id}','AdsDiagController#destroy');
Since Route::get('adsdiag/{id}/',AdsDiagController#create); is not generated by Resourcce so you need to include in your route explicitly.
You need to pass the arguments to the action() helper method in an array, even if it's just one argument:
action('AdsDiagController#create', [$record->id])
Related
I'm using Laravel and I have a question running on my mind.
Basically, we create a Controller method like this:
public function index(User $user)
{
if(!empty($user)){ ... }
...
}
And we call this method by passing the $user as parameter to this method.
But is it possible to call the parameter optional. I mean if $user didn't pass, still the method works.
So in order to do that, do we have to create two web routes? Because by default, when we pass parameter we have to define that too in the route uri:
Route::get("/{user}", "HomeController#index");
Route::get("/", "HomeController#index");
So how to do this in Laravel? Is it possible or not?
I would really appreciate any idea or suggestion from you guys...
Thanks.
You can make a method parameter optional, yes. That's a PHP feature:
PHP - default function/method parameters
So in your code:
public function index(User $user = null)
{
if(!empty($user)){ ... }
...
}
It seems you want to call HomeController#index in both cases, isn't that misleading? If you visit /1 it will load user with ID 1 and show the homepage. What could be the use-case of that?
As John Lobo suggested, the route should better be /user/{user} to remove that ambiguity.
As an aside: Use Auth to get current user
If this is meant to load the current user: You can load the current user in every controller with Auth. There is no need to pass the user explicitly as a parameter if that works better for you:
$user = Auth::user();
See Laravel docs: Authentication
I'm trying to call controller with href, but I'm getting error, I need pass a parameter.
Im doing like this
<i class="material-icons" title="Delete"></i>
Controller Code
public function destroy(Story $story)
{
$story = Story::find($id);
$story->delete();
return redirect('/stories')->with('success', 'Historic Removed');
}
Error Missing required parameters for Route: stories.destroy -> error
The link_to_action() helper generates an actual HTML link, which is an <a> tag. You're therefore already using it wrong.
However the error you're getting is likely not related to this.
The best way to link to routes is using the route() helper:
link
And the route definition:
Route::get('/someroute/{:param}', ['uses' => 'IndexController#index', 'as' => 'index.index']);
Note the as key, it assigns a name to this route. You can also call
Route::get(...)->name('index.index')
which yields the same result.
I might be wrong but in html you're passing an integer, in controller though, function is expecting an object of Story. Just change Story story to $id and it should be good.
Anyway, can't say much more without actual error.
Since you are accepting $story as model object so you don't have to use Story::find() and also you haven't define $id in your destroy method therefor Change your code to:
public function destroy(Story $story)
{
$story->delete();
return redirect('/stories')->with('success', 'Historic Removed');
}
Hope it helps.
Thanks
You should use it in this way: since according laravel explanation for function link_to_action first param will be controller function path, 2nd will be name and 3rd will be array of required params:
<i class="material-icons" title="Delete"></i>
You can also get help from here
I am new to Laravel 5 and I am trying to use the new Form Request to validate all forms in my application.
Now I am stuck at a point where I need to DELETE a resource and I created a DeleteResourceRequest for just to use the authorize method.
The problem is that I need to find what id is being requested in the route parameter but I cannot see how to get that in to the authorize method.
I can use the id in the controller method like so:
public function destroy($id, DeletePivotRequest $request)
{
Resource::findOrFail($id);
}
But how to get this to work in the authorize method of the Form Request?
That's very simple, just use the route() method. Assuming your route parameter is called id:
public function authorize(){
$id = $this->route('id');
}
You can accessing a Route parameter Value via Illuminate\Http\Request instance
public function destroy($id, DeletePivotRequest $request)
{
if ($request->route('id'))
{
//
}
Resource::findOrFail($id);
}
Depending on how you defined the parameter in your routes.
For my case below, it would be: 'user' not 'id'
$id = $this->route('user');
Laravel 5.2, from within a controller:
use Route;
...
Route::current()->getParameter('id');
I've found this useful if you want to use the same controller method for more than one route with more than one URL parameter, and perhaps all parameters aren't always present or may appear in a different order...
i.e. getParameter('id')will give you the correct answer, regardless of {id}'s position in the URL.
See Laravel Docs: Accessing the Current Route
After testing the other solutions, seems not to work for laravel 8, but this below works
Route::getCurrentRoute()->id
assuming your route is
Route::post('something/{id}', ...)
I came here looking for an answer and kind of found it in the comments, so wanted to clarify for others using a resource route trying to use this in a form request
as mentioned by lukas in his comment:
Given a resource controller Route::resource('post', ...) the parameter you can use will be named post
This was usefull to me but not quite complete. It appears that the parameter will be the singular version of the last part of the resource stub.
In my case, the route was defined as $router->resource('inventory/manufacturers', 'API\Inventory\ManufacturersController');
And the parameter available was manufacturer (the singular version of the last part of the stub inventory/manufacturers)
you will get parameter id if you call
request()->route('id')
OR
$this->route('id')
if you're using resource routing, you need to call with the resource name
// eg: resource
Route::resource('users', App\Http\Controllers\UserController::class);
$this->route('user')
in Terminal write
php artisan route:list
to see what is your param name
Then use
$this->route('sphere') to get param
In Laravel, we can get route name from current URL via this:
Route::currentRouteName()
But, how can we get the route name from a specific given URL?
Thank you.
A very easy way to do it Laravel 5.2
app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1'))->getName()
It outputs my Route name like this slug.posts.show
Update: For method like POST, PUT or DELETE you can do like this
app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST'))->getName()//reference https://github.com/symfony/http-foundation/blob/master/Request.php#L309
Also when you run app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST')) this will return Illuminate\Routing\Route instance where you can call multiple useful public methods like getAction, getValidators etc. Check the source https://github.com/illuminate/routing/blob/master/Route.php for more details.
None of the solutions above worked for me.
This is the correct way to match a route with the URI:
$url = 'url-to-match/some-parameter';
$route = collect(\Route::getRoutes())->first(function($route) use($url){
return $route->matches(request()->create($url));
});
The other solutions perform bindings to the container and can screw up your routes...
I don't think this can be done with out-of-the-box Laravel. Also remember that not all routes in Laravel are named, so you probably want to retrieve the route object, not the route name.
One possible solution would be to extend the default \Iluminate\Routing\Router class and add a public method to your custom class that uses the protected Router::findRoute(Request $request) method.
A simplified example:
class MyRouter extends \Illuminate\Routing\Router {
public function resolveRouteFromUrl($url) {
return $this->findRoute(\Illuminate\Http\Request::create($url));
}
}
This should return the route that matches the URL you specified, but I haven't actually tested this.
Note that if you want this new custom router to replace the built-in one, you will likely have to also create a new ServiceProvider to register your new class into the IoC container instead of the default one.
You could adapt the ServiceProvider in the code below to your needs:
https://github.com/jasonlewis/enhanced-router
Otherwise if you just want to manually instantiate your custom router in your code as needed, you'd have to do something like:
$myRouter = new MyRouter(new \Illuminate\Events\Dispatcher());
$route = $myRouter->resolveRouteFromUrl('/your/url/here');
It can be done without extending the default \Iluminate\Routing\Router class.
Route::dispatchToRoute(Request::create('/your/url/here'));
$route = Route::currentRouteName();
If you call Route::currentRouteName() after dispatchToRoute call, it will return current route name of dispatched request.
how can I redirect from my controller to a named route and include variables in the URL, e.g.
return Redirect::to('admin/articles/create/'.$article_type.'/'.$area_id.'/'.$area_type);
this works, but I think that I missed a shortcut or something?
In Laravel 5, you can use the helper methods:
return redirect()->route('route.name', [$param]);
You can use Redirect::route() to redirect to a named route and pass an array of parameters as the second argument
Redirect::route('route.name',array('param1' => $param1,'param2' => $param2))
Hope this helps.
In Laravel 9 you can use the to_route() helper function.
return to_route('route.name', [$param]);
You can try this :
return redirect()->route('profile', [$user]);
This can help also if you are trying to redirect user to a profile with the id.