Laravel route optional parameter issue - laravel

My route is:
Route::get('members/{name?}/{id}', 'Sample1Controller#sampleFn1');
Route::get('members/{id}/edit', 'Sample2Controller#sampleFn2');
When i click the url link from blade,
Edit
it goes to the first route and calls Sample1Controller#sampleFn1. Why?? Please help..
When I click the link..I want to go the second route and calls Sample2Controller#sampleFn2. Any help?
Thanks in advance.

You need to add route where condition to parameters. First I quess is for stings, the second for integers:
Route::get('members/{name?}/{id}', 'Sample1Controller#sampleFn1')->where([
'name' => '[a-z]+',
'id' => '[0-9]+',
]);
Route::get('members/{id}/edit', 'Sample2Controller#sampleFn2')->where([
'id' => '[0-9]+'
]);

Route::get('members/{name?}/{id}', 'Sample1Controller#sampleFn1');
Both URL's look the same for laravel, in this case, $name is being set to "1" and $id is being set to "edit".
You need to avoid ambiguity by moving the optional parameter to the end
And the status text one level back, in this case:
Route::get('members/edit/{id}', 'Sample2Controller#sampleFn2');
Route::get('members/{id}/{name?}', 'Sample1Controller#sampleFn1');

It's not validating name or id against any specific constraints so you're /1/edit qualifies... to use the same route definitions you can simply reverse the order of the definitions.

try the following:
Route::get('members/{id}/edit', 'Sample2Controller#sampleFn2');
Route::get('members/{name?}/{id}', 'Sample1Controller#sampleFn1');

Route::get('/post-delete/{post_id}',[
'uses' => 'PostController#getDeletePost',
'as' => 'post.delete',
'middleware' => 'auth'
]);
My controller is like this
public function getDeletePost($post_id)
{
$post = Post::where('id',$post_id)->first();
if(Auth::user() != $post->user)
{
return redirect()->back();
}
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Sucessfully Deleted Taunt']);
}
and my blade.php is like this
Delete
the above code is for delete u c an try it for edit

Related

Missing required parameters for [Route: reviews.show] (from controller)

i want to route a new page from controller, i am getting data successfully when passing in route but getting error.
here is my particular part of controller -
$use = User::find($user->id);
$pos = posts::find($post->id);
//dd($user1, $post1);
return redirect()->route('reviews.show', $pos, $use);
in web.php part -
Route::get('p/{posts}/review/{user}','ReviewController#show')->name('reviews.show');
in show method -
public function show($posts, $user)
{
return view('posts.reviews.reviewshow', ['posts' => $posts], ['user' => $user]);
}
You have to use like this
return redirect()->route('reviews.show', ['posts' => $pos, 'user' => $use]);
route() calls in general take URL parameters as associative array. You are using helper function for it, but it still applies.
redirect()->route('reviews.show', ['posts' => $pos, 'user' => $use]);
When you pass 2 paramters to a route you send them as Array
return redirect()->route('reviews.show', [ $pos, $use ]);
This is your issue

Laravel Best Practice: Print Json response

I've been wondering what is the best way in Laravel to return a json array back to an ajax call. This is the way I'm working right now:
Route in web.php
Route::group(['prefix' => 'users'], function () {
Route::post('getOneTimeLink', [
'as' => 'adminUserOneTimeLink',
'uses' => 'AdminUsersController#createOneTimeLink'
]);
});
Controller in AdminUsersController.php
public function createOneTimeLink(){
$aResponse = [ 'someData' => 'someValue'];
// do some stuff here
echo json_encode($aResponse);
die()
}
but I think there is another way to return the call instead of adding the json_encode then die() the execution... but I don't know it yet. I've tried to search but haven't yet found an answer. I hope any of you can help me.
Thank you so much!
return response()->json($aResponse);
More information: https://laravel.com/docs/5.5/responses#json-responses
Please try to embed this logic into your code:
$response = array( 'status' => 'success', 'message' => $Info );
return response() ->json($response)->withHeaders($this->headerArray);

Laravel router with additional parameters

I have controller which called by this route website.lrv/products/{category-url}
public function categoryProducts($uri, Request $request) { /** some code **/ }
I have a few links that are responsible for ordering products, i added them directly to blade template, like this:
route('client.category.products', [
'url' => Route::current()->url,
'order' => 'article',
'by' => 'desc' ])
route('client.category.products', [
'url' => Route::current()->url,
'order' => 'article',
'by' => 'asc' ])
And the request link with ordering is:
website.com/products/chargers?order=name&by=asc
Now i want to add products filters. I have many filters, each filter can contain many values. The problem is that i don't know how to make route to get some like that:
website.com/products/chargers?width=10,20,30&height=90,120,150
or something like that.
I need to get request array like that:
$request = [
....
filters => [
width => ['10','20','30'],
height => ['90','120','150'],
],
....
];`
If you need some additional info, i will edit my question.
You can access the array you are looking for by using $request->query() within the categoryProducts function.
Edit: Also worth noting you can access them from within your blade template using the Laravel helper function request(), so {{ request()->query('width') }} would return xx where website.lrv/products/category?width=xx.
Edit 2: Note that if your query string includes commas per your example width=10,20,30 the query() will just return a comma separated string, so you would need to explode(',',$request->query('width')) in order to get the array of widths
I think you have to add them manually like this:
route('client.category.products')."?order=name&by=asc";
Try this I hope it help.

How do I define an optional parameter in my Laravel routes?

I would like to define {id} an optional parameter in the following route:
Route::get('profile/edit/{id}', array('uses' => 'BusinessController#editProfile', 'as' => 'profile.edit'));
How can I do this and also define a default parameter if one isn't provided?
Just like the other answers, but as for the default part: I asked almost the same question a few days ago and the answer is:
Route::get('profile/edit/{id?}', array('uses' => 'BusinessController#editProfile', 'as' => 'profile.edit'))
->defaults('id', 'defaultValue');
The important things are
The questionmark
The defaults function
Route::get('profile/edit/{id?}', array('uses' => 'BusinessController#editProfile', 'as' => 'profile.edit'));
you can pass {id?} for optional parameters in your route.
Laravel will take it as a optional. it is called as a wild card in laravel
Just put a question mark after it in the route, and give it a default in the function:
Route::get('profile/edit/{id?}', ...
public function editProfile ($id = 123) { ... }
Documentation: https://laravel.com/docs/5.4/routing#parameters-optional-parameters

Get a parameter from a route?

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.

Resources