I am making an online shop, so it has products. I am outputing all the products images and their names and I want when the user clicks on the product to redirect him to a single-product page the problem I have is passing the id of the product to the single-product view.
Here's my code Routing:
Route::get('single', [
"uses" => 'ProductsController#single',
"as" => 'single'
]);
Index.blade.php:
See product
And the controller:
public function single($product_id)
{
$product = Product::where('product_id', $product_id);
return view('single-product', compact("product"));
}
You need to capture segments of the URI within your route.
Route::get('single/{id}', [
"uses" => 'ProductsController#single',
"as" => 'single'
]);
Make changes to your route as given below:
Route::get('single/{product_id}', [
"uses" => 'ProductsController#single',
"as" => 'single'
]);
If you want to pass any parameters to your route then you've to assign placeholders for the parameters, so in your case, the {product_id} will be used as the placeholder which will be used to take the parameter from the URI, for example: http://example.com/single/1. So, you'll receive the 1 as $product_id in your single method.
Related
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
]);
Normally while using resource route for example like this:
Route::resource('somethings','SomethingsController' );
The url here which is displayed in browser in http://localhost:8000/somthings/create but what want is to display like this:
http://localhost:8000/somthings basically I dont want create in the url.
You can't change URL while using Route::resource(). You'll need to define all routes manually:
Route::get('somethings', 'SomethingsController#createSomething');
https://laravel.com/docs/9.x/controllers#restful-localizing-resource-uris
App\Providers\RouteServiceProvider
file, boot add the following;
public function boot()
{
Route::resourceVerbs([
'create' => 'oluştur',
'edit' => 'düzenle',
]);
// ...
}
To change route names in resource:
Route::resource('somethings', 'SomethingsController', [
'names' => [
'index' => 'somethings.index',
'store' => 'somethings.store',
...
]
]);
I have this route defined inside a group
Route::group(['domain' => '{subdomain}.test.com'], function () {
Route::get('/models/{id?}', [
'as' => 'car-model',
'uses' => 'CarModelController#details'
]);
});
I want to avoid hardcoding URLs in blade
{{route('car-model', 'ford', '100) }}
but that returs this url
ford.test.com/models
no model id!
Not sure if is relevant but in my controller CarModelController.php
I defined
public function details($subdomain, $id)
why is not sending the id to the generated url? Do I need to send the $subdomain parameter to the detail function?
I found that
{{route('car-model', ['make' => 'ford', 'id' => '100]) }}
works! thanks for watching :)
I have to support url friendly structure for a project.
There is multiple tables with a slug column, in cakephp how can I route the slug to a controller in the most efficient way.
At first I was checking if slug exist in a table, if slug exist use the route:
$c = TableRegistry::get('cateogories');
$result= $c->find()->select(['id'])->where(['url'=>$slug])->toArray();
if(count($result) > 0) {
$routes->connect(
'/:slug',
['controller' => 'Categories', 'action' => 'index', 'id' => $result[0]['id']]
);
}
The problem being that I have multiple checks like the one above and each one is being ran even if a route prior matches (doesn't need to be ran so extra querys are being called).
So how can I add a conditional statement of some sort so that it only checks if the route matches if none of the prior ones have.
I'd suggest to go for a custom route class that handles this. While you could query the data in your routes files, this is
not overly test friendly
not very DRY
not safe for reverse routing
The latter point means that when not connecting all routes, trying to generate a URL from a route array for a non-connected route might trigger an exception, or match the wrong route.
With a custom route class you could simply pass the model in the options when connecting the routes, and in the route class after parsing the URL, query that model for the given slug, and return false or the parsed data accordingly.It's really simple, just have a look at what the existing route classes do.
Here's a very basic example which should be pretty self-explantory.
src/Routing/Route/SlugRoute.php
namespace App\Routing\Route;
use Cake\Routing\Route\Route;
use Cake\ORM\Locator\LocatorAwareTrait;
class SlugRoute extends Route
{
use LocatorAwareTrait;
public function parse($url)
{
$params = parent::parse($url);
if (!$params ||
!isset($this->options['model'])
) {
return false;
}
$count = $this
->tableLocator()
->get($this->options['model'])
->find()
->where([
'slug' => $params['slug']
])
->count();
if ($count !== 1) {
return false;
}
return $params;
}
}
This example assumes that in the controller, you'd use the slug to retrieve the record. If you'd wanted to have the ID passed, then instead of using count(), you could fetch the ID and pass it along in the parsed data, like:
$params['pass'][] = $id;
It would then end up being passed as the second argument of the controller action.
routes.php
$routes->connect(
'/:slug',
['controller' => 'Articles', 'action' => 'view'],
[
'pass' => ['slug'],
'routeClass' => 'SlugRoute',
'model' => 'Articles'
]
);
$routes->connect(
'/:slug',
['controller' => 'Categories', 'action' => 'view'],
[
'pass' => ['slug'],
'routeClass' => 'SlugRoute',
'model' => 'Categories'
]
);
// ...
This would first check the Articles model, then the Categories model, etc., and stop once one of the routes finds a record for the given slug.
See also
Cookbook > Routing > Custom Route Classes
API > \Cake\Routing\Route::parse()
Source > \Cake\Routing\Route
I'm using CakePHP 3 and I want to paginate my users.
However when I click on the second page, the URL looks like /users?page=2 and I expect : /users/2.
I created this route in routes.php :
$routes->connect('/users/:page', ['controller' => 'users', 'action' => 'index'], ['page' => '[0-9]+']);
And in Users/index.ctp before the "prev" button I put :
<?php
$this->Paginator->options([
'url' => [
'controller' => 'users',
'action' => 'index'
]
]);
?>
Now when I click on page 2 for example, /users/2 opens and I got this error message (RuntimeException) :
Unable to locate an object compatible with paginate.
Did I miss something or where I made a mistake ?
Thanks for your help.
The PaginatorHelper has built in the url format, i.e. to use ?page=n. It will also do sorting such as users?page=2&sort=user_id&direction=asc. Your format of /users/{page} does not handle sorting.
If your REALLY want to stick to /users/{page} you'll have to override PaginatorHelper.
try this
in side your controller with paginator component . It works for me
$this->Paginator->paginate('Users')
for custom urlenter code here
u need to implement index action as
public function index($page = null){
$this->Paginator->settings = ['limit' => 15, 'page' => $page];
$this->set('users', $this->Paginator->paginate('Users'));
}