PHP How to create urls properly? - php

I have never understood how to create proper URLs. Every time I end up with trying to figure out if I should do ?var=value or &var=value and then if ?var=value already exists then I end up with ?var=value&var=value.
P.S. I am working with Laravel. (So maybe there is a built-in function?)
For example:
I have pagination and my URL could look like this
www.example.com OR
www.example.com?name=John
Then my pagination link is href="?page=2" and I end up with
www.example.com?name=John?page=2
Then I want to navigate to the next page with href="?page=3" and I end up with this. Because it keeps on adding.
www.example.com?name=John?page=2?page=3
What a mess.... is there a function for PHP or Laravel that would create proper URLS? (knowing when to use ? or & and not add existing values all the time but replace them if they exist already.

If you're using Laravel I think you should use some helper functions:
route('user.profile', ['id' => 1]);
It will create url by route name and parameters, It will look like:
http://sitename/user/profile?id=1
And you can find some useful helper functions here

There should be one and only ? in URL's which separates URI and parameters, rest of the key-value pairs are separated by &, and if you need to pass & or ? as a parameter, then you need to encode them.
you could pass an array to http_build_query and it will build the url for you
and in laravel there are url helper functions you can use them with ease.

Laravel come with a route helper which allow you to generage url quickly by passing the name with which you register your route.
Route::get('/', 'HomeController#index')->name('home.route')
Here you can see I pass home.route to the name method which is the name which I use for this route. And when I want to generate the URL for that route in my view I will juste do
{{ route('home.route') }}
If ny route take some parameters like this
Route::get('/person/{id}', 'HomeController#index')->name('home.route')
In view I will generate the url like this
{{ route('home.route', ['id' =>$id]) }}
Because you want juste to make pagination, Laravel comme with a buil in pagination. When you want to paginate something in your views, you must just call the paginate function on your model and laravel will handle all the route for that. For example I you have a Person Model you can do that like this in your controller
$persons = Person::paginate(25)
And in your views to generate pagination for that you will have to do
{{ $persons->links() }}
And that's all

Related

What are some use cases of Named Routes in Laravel?

After reading the documentation, I still only have a vague idea of what Named Routes are in Laravel.
Could you help me understand?
Route::get('user/profile', function () {
//
})->name('profile');
Route::get('user/profile', 'UserProfileController#show')->name('profile');
It says:
Once you have assigned a name to a given route, you may use the route's name when generating URLs or redirects via the global route function
I don't understand what the second part of the sentence means, about generating URLs or redirects.
What would be a generated URL in the case of profile from the above example? How would I use it?
The best resource is right here : https://laravel.com/docs/5.8/routing#named-routes
One of the common use case is in your views. Say your post request goes to a particular route, basically without named routes you can simply go like this to store a task
action="/task"
but say for example you need to update the route to /task/store , you will need to update it everywhere you use the route.
But consider you used a named route
Route::post('/task', 'TaskController#store')->name('task.store');
With named routes you can use the route like this in your view:
action="{{route('task.store')}}"
Now if you choose to update your route, you only need to make the change in the routes file and update it to whatever you need.
Route::post('/task/now/go/here', 'TaskController#store')->name('task.store');
If you need to pass arguments to your routes, you pass it as arguments to route helper like this:
route('task.edit', 1), // in resource specific example it will output /task/1/edit
All of the view examples are given you use blade templating.
After adding a name to a route, you can use the route() helper to create urls.
This can now be used in your application.
For instance, in your blade templates this may look like:
{{ route('profile') }}
This will use the application url and the route path to create a url.
this is how it looks it:
named route sample name('store');:
Route::get('/store-record','YourController#function')->name('store');
store is the named route here. to call it use route('store')
defining another type of route. this is not named route:
Route::get('/store-record','YourController#function')
you can access this route using {{ url('/store-record') }}
hope this helps

Route my form action into a custom function created inside a resource controller

In my web.php,
Route::get('studentmarksheet/addit','StmarksheetController#addit');
Route::resource('studentmarksheet','StmarksheetController');
I created a custom function addit() inside StmarksheetController. I have a form inside a view where I need to pass values to that addit function. For default functions inside my resoource controller, I used to call by
but, while trying to pass form values in addit function, it says route not defined. What exactly should I write? I have tried
{{route('studentmarksheet/addit')}}
{{route('studentmarksheet#addit')}}
and various other combinations.
I am a total beginner and I don't even know if am questioning this correctly. Please share your answers/suggestions/tips and so on, I would love to read them all.
First you need to name a route
Route::get('studentmarksheet/addit','StmarksheetController#addit')->name('stmarksheet.addit');
Then call it
{{route('stmarksheet.addit')}}
Resource route are named for you by Laravel
You didn't set any name for the addit route. So, you need to write your route as like.
Route::get('studentmarksheet/addit','StmarksheetController#addit')->name('stmarksheet.addit');
And then you can get it in the view.
{{ route('studentmarksheet#addit') }}

Create a Dynamic URL and Redirect to it in Laravel

So basically this is what I need. I have a router definition like this.
Route::get('view/{postId}', 'PostController#view');
Above router definition will get triggered if the url we request is www.domain.com/view/4. But what I want is I want to appear this url like www.domain.com/[category-of-post]/[titile-of-post] (Ex : www.domain.com/music/easy-chords-in-guitar).
In PostController, I will get the post using the id passed and thus can generate the url what I need. Here is the problem begins. As you can see, I need to redirect to a dynamic url which will look differently for each post. I want to redirect to this dynamic urls but these urls are not defined inside routes.php.
Is this possible in Laravel ?
In short, what I need is, I want to update Illuminate\Routing\RouteCollection::$route array with my dynamically generated url value with corresponding controller action in run time before I am invoking Redirect::to('someurl')
If you need further clarification, I will do it for sure. Please give me your suggestions.
it is simpler than you are thinking.
Route::get('{category}/{title}',['uses' => 'FooController#bar']);
This should be the last route defined in your route list. Any other route should go upper than this one.
this will match www.domain.com/music/easy-chords-in-guitar
rest routes define as you want.
e.g.
Route::get('/',['uses' => 'FooController#home']);
Route::get('about',['uses' => 'FooController#about']);
Route::get('contact',['uses' => 'FooController#contact']);
Route::get('{category}/{title}',['uses' => 'FooController#bar']);
route :
Route::get('action/{slug}', 'HomeController#actionredeemvoucher')->name('home.actionredeemvoucher');
Function in controller:
public function actionredeemvoucher($slug)
{
print_r($slug);
}

Laravel multiple route aliases

I'm trying to create a route with an array of aliases, so when I call whois or who_is in the url it goes to the same route.
Then I don't need to keep repeating the code every time, changing only the alias.
I tried the code below.
Variables in the routes:
$path = 'App\Modules\Content\Controllers\ContentController#';
$aliases['whois'] = '(quemsomos|who_is|whois)';
Routes:
Route::get('{whois}', array('as' =>'whois', 'uses' => $path.'getWhois'))->where('whois', $aliases['whois']);
this one works as well
Route::get('{whois}', $path.'getWhois')->where('whois', $aliases['whois']);
Typing in the url my_laravel.com/whois or my_laravel.com/who_is or my_laravel.com/quemsomos will send me to $path.'getWhois' (which is correct).
But when I try to call it in the html on blade...
Who we are
The reference link goes to my_laravel.com//%7Bwhois%7D
How could I call route('whois') on my blade.php and make it work like when I type it on the url ?
I would like to use the route function` in my blade, so I can keep a pattern.
During route generation using the route function, Laravel expects you to set the value of the route parameter. You are leaving the parameter whois empty so the parameter capturing {whois} will not be replaced and results in the %7B and &7D for the accolades.
So in order to generate a route you will need to define what value you'd like to use for whois; {{ route('whois', ['whois'=>'whois']) }} for instance.

Route::controller with optional parameters in Laravel 4

I'm just new to Laravel but I immediately fell in love with it. As a not so super experienced php developer I do find the official documentation, although very expansive, somewhat complicated to use and find everything I need.
My question is about the Routing component. As the documentation states you can assign a route to a controller with the Route::controller method. So if I want a Blog controller for all /blog/ routes I assign it like this:
Route::controller('blog', 'BlogController');
So then if I'd like to acces all my blog posts I acces the the getIndex method by www.foo.com/blog or www.foo.com/blog/index
But let's say I'd like to be able to display categories via a getCategory method. My url would look like www.foo.com/blog/category and if, for example, I want to get the news category from the DB by slug, I'd like to use: www.foo.com/blog/category/news as the URI.
My question now is, how do I pass the slug to the url and access it in the getCategory method? Do I need specify it via Route::get('blog/category/{slug}', 'BlogController#getCategory') or is there a way to use Route::controller('blog', 'BlogController') and to send and acces parameters from the URL in the getCategory method?
I already tried to find it via google and in the official documentation, but I couldn't find a crystal clear answer to this problem...
You can simply add parameters to your getCategory method:
public function getCategory($category) {
die($category);
}
If you initialize it to null in the parameter list, it becomes optional. Alternatively, you can always pull parameters from the Input object but they would need to be passed in querystring format:
$category = Input::get('category');
With that said, I'd caution against using the Controller route. It's handy and mimics traditional MVC frameworks, but I believe it's planned to be deprecated -- and honestly, you miss out on some pretty flexible features.
using Route::controller('blog', 'BlogController'); allows you to define a single route to handle every action in a controller using REST naming conventions.then you have to add methods to your controller, prefixed with the HTTP verb they respond to. That means if you have a method called getIndex() it will be executed when there is a GET request to the url "yoursite.com/blog".
To handle POST requests to the same url add a method prefixed with post(ex: postComment()) and so on for other http verbs PUT, PATCH and DELETE.
I think you want something more customized, so you can use a resource controller:
Route::resource('blog', 'BlogController');
This will generate some RESTful routes around the blog resource, run php artisan routes in your project folder to see the generated routes, it should be something like this:
Verb Path Action Route Name
GET /blog index blog.index
GET /blog/create create blog.create
POST /blog store blog.store
GET /blog/{blog} show blog.show
GET /blog/{blog}/edit edit blog.edit
PUT/PATCH /blog/{blog} update blog.update
DELETE /blog/{blog} destroy blog.destroy
in the action column are the functions that you should have in the controller.
If you want to define more routes you can simply do it with Route::get or Route::post in the routes.php file
I hope this will make it more clear for you, enjoy routing with Laravel!!!

Categories