I use REST api for CRUD.
When I Use return redirect after CRUD, Laravel does not send me variable with
I don't want use session.
My code
return redirect("inventories")->with([ 'Tab' => 5,'flag' => 'success', 'flagMsg' => 'delete_successful', 'Inventories' => $Inventory]);
and when I use return view, Laravel send me variable but URL not change
and I want redirect and change URl
for example my URL is /inventories/2/edit and after update send me to /inventories/update and I want to redirect inventories
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
]);
Related
I am trying to follow best practice for REST api on CRUD.
GET: users/ -> all
GET: users/:id -> one specific user.
POST: users/ -> add one
PUT: users/:id -> update specific user.
DELETE: users/:id -> delete one user.
On laravel 8 I want to validate the url :id using the validator, so I have like this on delete user:
$validator = Validator::make(['id' => $request->id], [
'id' => 'exists:users,id,deleted_at,NULL',
]);
And this way to update a user:
$validator = Validator::make(array_merge($request->all(), ['id' => $request->id]), [
'id' => 'required|exists:users,id,deleted_at,NULL',
'name' => 'required',
'surname' => 'required',
'email' => 'required|email:rfc,dns'
]);
As you can see I have to put the id on an array and/or merge with the $request->all().
There is any way in laravel to do this with the request?
I have found 3 ways by Laravel:
$request->add(['variable' => 'value']);
$request->merge(["key"=>"value"]);
$request->request->set(key, value);
But a solution for adding route params to the request before hitting the controller method would be even great.
You can update the request object on the fly and add the ID field, before you validate it, something like
$request['id'] = $id;
// note: the $id is your function's parameter name
$validator = Validator::make(array_merge($request->all()), [
'id' => 'required|exists:users,id,deleted_at,NULL',
'name' => 'required',
'surname' => 'required',
'email' => 'required|email:rfc,dns'
]);
You can do it like you are doing, but doing it with route model binding would be the way to go.
Now when you want to update a user by sending a PUT to /users/:id, and the user does not exist you will get a 422. But what you really want would be a 404.
With route model binding, Laravel will check if the model exists for you and abort with a 404 when it does not.
If route model binding is not an option, you can also just not validate the id with the validator and retrieve the user with User::findOrFail($request->input('id')), the framework will then still abort with a 404 if it can't be found.
I have the following code where I want to find a model using a field called link instead of id. However, it doesn't seem to produce any results. Where could I be getting it wrong? It returns 404
public function actionView($link)
{
$model = News::find()->where(['link'=>$link])->all();
return $this->render('view', [
'model' => $model,
]);
}
NB: in the search model, I have tried adding this:
$query->andFilterWhere([
'id' => $this->id,
'link'=>$this->link,
'category' => $this->category,
'date' => $this->date,
'userid' => $this->userid,
'featured' => $this->featured,
]);
If you want a single model you need one() and not all()
public function actionView($link)
{
$model = News::find()->where(['link'=>$link])->one();
return $this->render('view', [
'model' => $model,
]);
}
With one() method you retrive just a model and in your $model you have the data you need ..
If you sue all() lie you did you retrive a collection of models and for accessing a single model you must set a proper index eg:
$my_model = $model[0];
In UrlManager config you propably have:
'<controller>/<action>/<id:\d+>' => '<controller>/<action>',
It means default rewrite rules use id as param and it has to be digit, so you can't use controller/view/link. Just to be sure, change action name from actionView to actionTest and then call URL controller/test?link=linklink.
Other solution is to use URL like this: controller/view?link=linklink
The problem is in your url
case 1)
http://localhost/projectName/backend/web/controllerName/actionName/username/rushil
Gives output : Not Found (#404)
case 2)
http://localhost/projectName/backend/web/controllerName/actionName/rushil
Gives output : Not Found (#404)
case 3)
http://localhost/projectName/backend/web/controllerName/actionName?username=rushil
this will work.
Solution : check your url and pass link parameter in url as shown in case 3
404 means your action was not found by url manager. link parameter must be in the url (http://yourapp/controller/view?link=something) because you definded it as actionView($link)
Requesting http://yourapp/controller/view will give you 404 error.
For anyone who may encounter such an error, the problem is after using pretty urls, you need to add rules to map the url format.
C:\xampp\htdocs\your_project\frontend\config\main.php under urlManager add the rules like so:
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => 'news/view',
'<controller:\w+>/<link>' => 'news/latestnews', // This is required for $link parameter
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>/<link>' => 'news/latestnews',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
],
I have a problem with Yii2's urlManager. I have an action with url category/index, where I pass ?par=test as param.
I want to create an alias for my url so that when par is not specified the url will be /test, but when it is specified the url should be /test/some-value. Here is my config for now:
'rules' => [
[
'pattern' => 'test',
'route' => 'category/index',
],
'<subcats: (val|some-value)>' => 'test/<subcats>',
If you need url like category/index/test/some-value. Use that
'category/index/test/<val:\w+>' => 'category/index'
In controller in method index use that:
public function actionIndex($val){
Yii2 automatically provide parameter $val in action.
I have one route that looks like this:
Router::connect('/Album/:slug/:id',array('controller' => 'albums', 'action' => 'photo'),array('pass' => array('slug','id'),'id' => '[0-9]+'));
and another like this:
Router::connect('/Album/:slug/*',array('controller' => 'albums','action' => 'contents'),array('pass' => array('slug')));
for what doesn't match the first. In the 'contents' action of the 'albums' controller, I take care of pagination myself - meaning I retrieve the named parameter 'page'.
A URL for the second route would look like this:
http://somesite.com/Album/foo-bar/page:2
The Above URL indeed works, but when I try to use the HTML Helper (url,link) to output a url like this, it appends the controller and action to the beginning, like this:
http://somesite.com/albums/contents/Album/foo-bar/page:2
Which i don't like.
The code that uses the HtmlHelper is as such:
$html->url(array('/Album/' . $album['Album']['slug'] . '/page:' . $next))
See below url it is very help full to you
http://book.cakephp.org/2.0/en/development/routing.html
Or read it
Passing parameters to action
When connecting routes using Route elements you may want to have routed elements be passed arguments instead. By using the 3rd argument of Router::connect() you can define which route elements should also be made available as passed arguments:
<?php
// SomeController.php
public function view($articleId = null, $slug = null) {
// some code here...
}
// routes.php
Router::connect(
'/blog/:id-:slug', // E.g. /blog/3-CakePHP_Rocks
array('controller' => 'blog', 'action' => 'view'),
array(
// order matters since this will simply map ":id" to $articleId in your action
'pass' => array('id', 'slug'),
'id' => '[0-9]+'
)
);
And now, thanks to the reverse routing capabilities, you can pass in the url array like below and Cake will know how to form the URL as defined in the routes:
// view.ctp
// this will return a link to /blog/3-CakePHP_Rocks
<?php
echo $this->Html->link('CakePHP Rocks', array(
'controller' => 'blog',
'action' => 'view',
'id' => 3,
'slug' => 'CakePHP_Rocks'
));
Is it possible to pass parameters via redirect? I tried a lot of options, but nothing seems to work. My latest approach is:
return $this->redirect(array('Users::helloworld', 'args' => array('id' => 'myId')));
then I created a route:
Router::connect('/Users/helloworld?id={:id}', array('controller' => 'Users', 'action' => 'helloworld'));
but all I get is users/helloworld/myId
args is part of the routes and will be converted into an URL using the very generic route (not the one you created and don't require)
To get a query string, simply use the ? key:
return $this->redirect(array(
'Users::helloworld',
'?' => array('id' => $myId)
));
// will use the route:
// /{:controller}/{:action}/{:args}
// and generate
// /users/helloworld?id=$myId
The test for that: https://github.com/UnionOfRAD/lithium/blob/master/tests/cases/net/http/RouteTest.php#L374-405
Instead of defining a separate route to pass arguments, you could just do the following.
Lets say you want to pass 2 arguments: $arg1 & $arg2 to the helloworld action of your Users controller:
return $this->redirect(array(
'Users::helloworld',
'args' => array(
$arg1,
$arg2
)
));