Laravel route in view and send autocomplete parameter to another page - laravel

I have two webpages A and B, A has a link button like this
Link
and B is a page about article lists, and has a table with column [#, books_name, author......]
And also, B has a query table to query data, user can input books_name or author_name, then it'll show the data user wants.
My question is, how to modify link in A Page and let it send autocomplete parameter to B?
The result of B's url may be like this
https://{B's path}/?q_author_name={the parameter from Page A}
Hope someone can help me. Thanks!

You can pass the query parameter as second argument to route()
{{ route('to_B', ['q_author_name' => 'Author']) }}
would generate
https://{B's path}?q_author_name=Author
provided you don't have any route parameters in your route definition like
Route::get("{B's path}/{param1}", function () {})->name('to_B');
in that case the first key from the route array would be passed to the param1 making your route as
https://{B's path}/Author

Related

How to convert CodeIgniter urls into user friendly ones?

I've explored lot of questions and articles regarding this but I can't find how to get this done.
I'm doing a website which provides specifications of several products such as phones, tablets, tv etc. Here's what I've:
Controller - Specs (create and display specification of all products)
Method - Display (fetches detailed specs of selected model and shows)
Method - Index (lists names of all models stored in the table. this is where I build anchor links)
Display method takes three arguments (1, 2, 3).
1 - Type of product (Phones, Tablets, TV etc)
2 - Model Slug (iphone-6, galaxy-tab-s3, bravia-kdl-50w800d etc)
3 - Model ID (1, 4, 13 etc)
My URLs right now are like this:
localhost/sitename/specs/display/phones/iphone-6/1
localhost/sitename/specs/display/tablets/galaxy-tab-s3/4
localhost/sitename/specs/display/tv/bravia-kdl-50w800d/13
What I want to achieve is URLs which are like this:
localhost/sitename/iphone-6
localhost/sitename/galaxy-tab-s3
localhost/sitename/bravia-kdl-50w800d
I don't mind restructuring my tables/controllers/methods or anything else if this can be achieved using whatever.
Thanks for reading.
Edit:
Route.php
$route['default_controller'] = 'Specs/index';
$route['404_override'] = 'Errors/show_404';
$route['translate_uri_dashes'] = FALSE;
This is how I'm building the anchor links (view_file->index.php, called from Index method):
<?php
foreach model(in the table)
echo anchor(specs_controller.display_function.product_type.model_slug.model_id, model_name);
end foreach
?>
I can get the desired URLs with following code in route.php. Only problem is I'm not able to make the 'urlController/urlMethod' return a value in the function which can be assigned to $result variable.
$route['(:any)'] = function ($1)
{
$result = 'urlController/urlMethod/'.$1;
return $result;
};
I'm not sure how to do this. Can someone suggest how I should call 'urlController/urlMethod'?
You could achieve it with CodeIgniter URI Routing. Considering
localhost/sitename/galaxy-tab-s3
maps to
localhost/sitename/specs/display/tablets/galaxy-tab-s3/4
And, model id i.e 4, in this case, is static with respect to galaxy tab s3, as you have not mentioned any such Id in the simplified URL.
My understanding is with every URL localhost/sitename/iphone-6, you need three details about the string 'iphone-6'. i.e. type of product, model-slug, model id. One way could be write something like
$route['sitename/(:any)'] = 'routingController/commonRoutingMethod/$1';
Here, create a new routingController and write some logic into commonRoutingMethod() method, which takes the string like iphone-6 and fetches its all three details i.e. product type, model id etc. And then redirects by building the exact URL using
header('Location: http://localhost/sitename/specs/display/$productType/$modelSlug/$modelId/');
NOTE : There could be more forward ways just using regex match in routes.php, given that you create diffrentiated structure of the string, based on product type and model id e.g p_iphone-6_1 or t_galaxy-tab-s3_4.
Please use below routing code, to achieve it.
localhost/sitename/specs/display/phones/iphone-6/1
localhost/sitename/specs/display/tablets/galaxy-tab-s3/4
localhost/sitename/specs/display/tv/bravia-kdl-50w800d/13
localhost/sitename/iphone-6
localhost/sitename/galaxy-tab-s3
localhost/sitename/bravia-kdl-50w800d
$route['(:any)'] = 'specs/display/$1/$1/$1';
Let me know if you need any help.

How to handle new incoming entries while paging through posts?

Let's assume I have a pagination like this
return App\Post::paginate(1);
After loading this someone creates a new entry in the database for posts. How can i ensure that the "second page" of my pagination does not return the first one again?
Will I always need to send a timestamp with every request to make an additional query before pagination is used?
like
App\Post::where('created_at', '<', $request->input('max_created_at'))->paginate(1);
You can use orderBy. You could do something like that:
// Get the last post (most recent)
return App\Post::orderBy('created_at', 'DESC')->paginate(1);
Or:
// Same as above
return App\Post::orderBy('created_at', 'DESC')->first();
orderBy means all you result are sorted in your query. Hope it will help.
You don't need to pass any timestamp value to verify pagination.
In the controller, in view file you need to pass result of this query.
$result = App\Post::orderBy('created_at', 'desc')->paginate(1);
return view('pagination',compact('result'));
In view file you need below line for pagination work automatically as per Laravel syntax.
{{ $result->links() }}
Visit https://laravel.com/docs/5.2/pagination/ how laravel pagination work.

ALERT SESSION VALUE FROM first page to 2nd page using JQuery,ajax, or javascript

hi guyz this is my first time here. ahmmm i'd like to ask some question regarding session. ahmm
how i cant alert session value from first page to 2nd page using jquery,ajax, or javascript??
please help, im new on that language. ):
You can pass value from one page to other using url query string.
one link to second page add data as parameter like http://your-url.com?data=user-session-value
in the second page call the below javascript function in onload or where you need value
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
you can alert the value like alert(getParameterByName('data'));
In this way your data will show in url. if you don't want to show it then use localstorage. But you need to be in same domain. I mean u can't pass data from one website to other.
In page one just set the data in local storage like localStorage.setItem('data', 'user-session-value');To alert the data in second page call alert(localStorage.getItem('data'));
Hope this can solve your issue... Happy coding...

Laravel routing url with variable order of parameters

I am looking at routing to a Controller for GET URL whose parameters can vary in number or the order in which they appear in the URL. There could be many such combinations and I want to invoke the same controller action for all of these URLs
Examples of how my URLs could look like:
Route::get('route1/id/{id}',
'Controller1#controllerAction1');
Route::get('route1/id/{id}/name/{name}',
'Controller1#controllerAction1');
Route::get('route1/name/{name}',
'Controller1#controllerAction1');
Route::get('route1/id/{id}/name/{name}/orderby/{orderby}',
'Controller1#controllerAction1');
Route::get('route1/id/{id}/orderby/{orderby}',
'Controller1#controllerAction1');
Also in the Controller action, I ultimately want to break this query string into an array. For the second example mentioned above, I want the query string id/{id}/name/{name} to be converted to array ('id' => {id}, 'name' => {name})
To invoke the same controller action for all different variations of the URLs, I have the following code in my routes.php:
Route::get('route1{all}', 'Controller1#controllerAction1')->where('all', '.*')
which seems to invoke the "controllerAction1" of Controller1 for the different types of URLs mentioned above.
And in the function controllerAction1, I am doing
$route_input = Route::input('all');
var_dump($route_input);
which prints "/id/1/name/xyz" when I hit http://example.com/laravel/public/route1/id/1/name/xyz
I would like to know if:
Doing Route::get('route1{all}',
'Controller1#controllerAction1')->where('all', '.*') is the right
method to invoke same action for variable combination of get
parameters? Does Laravel offer any function to convert
"/id/1/name/xyz" to array('id' => 1, 'name' => 'xyz') or I need to
write custom function? Is there a better way to achieve my
requirements?
I believe not. Plus, in this way you won't be able to understand which values are being passed.
Even if there is one, I think you don't actually need to pass the array. IMHO, I prefer to keep the items separate, then manipulate them from the controller. This is just my personal suggestion, but if you need an array of data, why don't you use a POST method? (the only right answer, is that you want the users to be able to save the link :P )
The complicated part about your request, is that you want to keep everything under the same controller action, which messes the routes. I would try this (in your routes.php):
Route::pattern('id', '[0-9]+');
Route::pattern('name', '[a-Z]+');
Route::get('route1/{id}/{name?}/{orderby?}', 'Controller1#controllerAction1');
Route::get('route1/{name}/{orderby?}', 'Controller1#controllerAction1');
In this way:
you can have a route with just the ID, where NAME and ORDERBY are optional
if no ID is passed, you can have a route with only NAME, where ORDERBY is optional
Note how this is different from your URLs: it's much more complicated to put the routes as you wrote them id/{id}/name/{name}, than in the way I proposed {id}/{name}. If you need them exactly your way, why don't you call the links passing the variables from the GET function as follows? http://www.yoursite.com/route1?id=xxxx&name=yyyy&orderBy=zzzz
To have the route parameters convert from a set of individual parameters to an array that contains all the parameters in Laravel 5, you can call this from the Controller:
$routeParameters = $this->getRouter()->getCurrentRoute()->parameters()
For the route definition
Route::get('route1/id/{id}/name/{name}', 'Controller1#controllerAction1');
if a user hits the route with the following: /route1/id/2/name/john
$routeParameters would equal
array(id => 2, name => 'john')

Grails chained drop down

I'm trying to implement chained drop down boxes using the tutorial here. My classes are not as straight forward as the ones in the tutorial though.
I want to chain the drop down boxes for the create.gsp view in the Load class. Each load belongs to an account from the Account class, and each account belongs to a user from the User class, and each user has several cargo destinations from the Address class.
My goal is to have the cargo destination field up date based on which account is selected.
I am having trouble understanding the AJAX function in the tutorial (step 3), and how it relates to the Grails function (step 4).
Here is the AJAX code:
function respondToSelect(event)
{
new Ajax.Updater("memberSelect",
"/chainedSelect/family/updateSelect",
{method:'get', parameters: {selectedValue : $F("familySelect")} }
);
}
Here is the Grails method:
def updateSelect = {
def familySelected = Family.find("from Family as family where family.surname=:surname", [surname:params.selectedValue])
render (template:"selectMember", model : ['familySelected' : familySelected])
}
If someone could just explain what the third parameter of the AJAX function is doing I think I can figure the Grails part out.
{method:'get', parameters: {selectedValue : $F("account")}}
If someone could just explain what the third parameter of the AJAX
function is doing
The third argument is an object of parameters that get passed to the Updater that tell it how to make the HTTP request to the server.
Make the request an HTTP GET request:
method:'get'
Pass the following named query parameters:
{selectedValue: $F("account")}
$F is a prototype shortcut to retrieve the value of an element. In this case, it's getting the selected value of the DOM element with id account.
This ultimately results in something like the following request:
GET /chainedSelect/family/updateSelect?selectedValue=someValue
Where "someValue" is the currently-selected item in the "account" select list.

Resources