I have a class named Collection with two methods named Index and Cars.
In it's basic format my controller it looks like this;
class Collection extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
public function index(){
$data = array(
'title' => 'Index Page'
);
$this->load->view('template/Header');
$this->load->view('collection/index', $data);
$this->load->view('template/Footer');
}
public function cars(){
$data = array(
'title' => 'Cars Page'
);
$this->load->view('template/Header');
$this->load->view('collection/list_of_cars', $data);
$this->load->view('template/Footer');
}
}
The URI looks like this;
example.com/collection/cars
This does what I want, the cars method is processed and the list_of_cars view is displayed as usual.
However I notice that if I add another parameter to the URL, e.g
example.com/collection/cars/something
In fact, I can add as many additional URI parameters as I like and I still don't get a 404 error.
The page simply reloads - should it not display a 404 error as that page doesn't exist?
Any advice is appreciated.
If your URI contains more than two segments they will be passed to your method as parameters.
The segment(s) you given is/are treated as arguments for the method you are accessing, means if you given like this
example.com/collection/cars/something
you can access this parameter in your cars method like this
public function cars($param)
{
echo $param;
}
and if you given like this
example.com/collection/cars/something/testing
you can access this parameter in your cars method like this
public function cars($param,$param2)
{
echo $param;
echo $param2;
}
Update :
If you want some check condition based on segments use $this->uri->segment() in your method , do like this :
if ($this->uri->segment(3) === FALSE)
{
/*this is your error page*/
$this->load->view('error-page');
}
else
{
$arg = $this->uri->segment(3);
}
For more : https://www.codeigniter.com/user_guide/libraries/uri.html
An approach that is similar can be structured as follows. If there are more than two segments (i.e. a controller + a method) then arguments are present so force a 404.
if ($this->uri->total_segments() > 2)
{
show_404(); //shows 404 page, logs the error, and ends execution
}
Read about show_404() here.
Related
I have created the following method in an News model in a Laravel project:
public function path() {
return route('news.show', $this);
}
Now, this works just fine and returns the following url structure: www.mydomain.com/news/{id}
However, I would like to tweak it a bit. I want my url structure to be like this: www.mydomain.com/news/{id}/{slug}
So, what I want to know is how do I have to modify the path function in order to return this url structure - i.e., the one with both the id and the slug?
Here is one solution that I tried:
// web.php
Route::get('news/{article}/{slug}', 'NewsController#show')->name('news.show');
// News.php
class News extends Model
{
public function path() {
return route('news.show', $this);
}
}
I then fire up tinker and run that path function and get the following error:
Illuminate/Routing/Exceptions/UrlGenerationException with message 'Missing required parameters for [Route: news.show] [URI: news/{article}/{slug}].'
I have tried other variations -- but nothing seems to work.
Any idea how to tweak this so that it does work?
Thanks.
// web.php
Route::get('news/{id}/{slug}', 'NewsController#show')->name('news.show');
You need to pass article id and slug
// News.php
class News extends Model
{
public function path() {
return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
}
}
I'm displaying user profiles on a PHP website using usernames as part of the URL that links to the given user profile.
I can achieve this through a controller, the ProfileController, but the URL will look like this thewebsite.com/profile/show_profile/ANYUSERNAMEHERE
What i want is something similar to Facebook, where the username is appended just after the base URL:
https://www.facebook.com/zuck
I tried passing a variable to the Index function (Index()) of the home page controller (IndexController), but the URL becomes thewebsite.com/index/ANYUSERNAMEHERE and the base url thewebsite.com throws an error:
Too few arguments to function IndexController::index(), 0 passed and exactly 1 expected.
The home page controller:
<?php
class IndexController extends Controller
{
public function __construct()
{
parent::__construct();
}
// IF LEFT, THE VARIABLE $profile THROWS AN ERROR AT THE BASE URL
public function index($profile)
{
/** AFTER REMOVING THE $profile VARIABLE ABOVE AND THE 'if'
* STATEMENT BELOW, THE ERROR THROWN AT THE BASE URL VANISHES AND
* THE WEBSITE GOES BACK TO IT'S NORMAL STATE. THIS CODE WAS USED
* TRYING TO RENDER THE URL thewebsite.com/ANYUSERNAMEHERE BUT IT
* ONLY WORKS WITH thewebsite.com/index/ANYUSERNAMEHERE
*/
if (isset($profile)) {
$this->View->render('profiles/show_profile', array(
'profiles' => ProfileModel::getSelectedProfile($profile))
);
} else {
$this->View->render('index/index', array(
'profiles' => ProfileModel::getAllProfiles()));
}
}
The profile controller:
<?php
class ProfileController extends Controller
{
public function __construct()
{
parent::__construct();
Auth::checkAuthentication();
}
public function index()
{
$this->View->render('profiles/index', array(
'profiles' => ProfileModel::getAllProfiles())
);
}
public function show_profile($profile)
{
if (isset($profile)) {
$this->View->render('profiles/show_profile', array(
'profiles' => ProfileModel::getSelectedProfile($profile))
);
} else {
Redirect::home();
}
}
}
I was expecting the base URL to pass the argument (the username) to the IndexController's Index($profile) function, but the webpage throws an error and the expected result is being displayed from the wrong URL: thewebsite.com/index/ANYUSERNAMEHERE
You would need to use a router based on regular expressions, like FastRoute, or Aura.Router.
For example, with FastRoute you'd define and add a route to the so-called route collector ($r) like this:
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
// The /{profile} suffix is optional
$r->addRoute('GET', '[/{profile}]', 'handler');
});
where handler is just a generic name for a customizable route handler in form of a callable. For example, if you'd additionally use the PHP-DI/Invoker library, the route handler ('handler') could look like one of the following callables (at least):
[ProfileController::class, 'show_profile']
'ProfileController::show_profile'
So the complete route definition would be like:
$r->addRoute('GET', '[/{profile}]', [ProfileController::class, 'show_profile']);
$r->addRoute('GET', '[/{profile}]', 'ProfileController::show_profile');
The placeholder name (profile) corresponds to the name of the parameter of the method ProfileController::show_profile:
class ProfileController extends Controller {
public function show_profile($profile) {
...
}
}
Even though the URL would look like you want it, e.g. thewebsite.com/zuck, I imagine that the placeholder {profile} of the above route definition would come in conflict with the fixed pattern parts defined in other route definitions, like /books in:
$r->addRoute('GET', '[/books/{bookName}]', 'handler');
So I suggest to maintain a URL of the form thewebsite.com/profiles/zuck, with the route definition:
$r->addRoute('GET', '/profiles/{profile}', 'handler');
I also suggest to read and apply the PHP Standards Recommendations in your code. Especially PSR-1, PSR-4 and PSR-12.
how can i use same route for two different controller function methods in laravel
first controller
public function index()
{
$comproducts = Comproduct::paginate(6);
$items = Item::orderBy('name')->get();
return view('computer', compact(['comproducts', 'items']));
}
second controller
public function index()
{
return view('search.index');
}
i want to use these two different controller functions for one route.
This is my route name
Route::get('/computer', [
'uses' => 'ComputerProductsController#index',
'as' => 'computer.list'
]);
laravel needs somehow to identify which exactly method you want. for example you can pass the parameter, which will identify which method to call.
public function index(Request $request)
{
// if param exists, call function from another controller
if($request->has('callAnotherMethod')){
return app('App\Http\Controllers\yourControllerHere')->index();
}
$comproducts = Comproduct::paginate(6);
$items = Item::orderBy('name')->get();
return view('computer', compact(['comproducts', 'items']));
}
You can't. If you want to add search functionality to your first controller's index page, you should determine which page to show inside your controller.
A possible example controller:
public function index(Illuminate\Http\Request $request)
{
// If the URL contains a 'search' parameter
// (eg. /computer?search=intel)
if ($request->has('search')) {
// Do some searching here and
// show the search results page
return view('search.index');
}
$comproducts = Comproduct::paginate(6);
$items = Item::orderBy('name')->get();
return view('computer', compact(['comproducts', 'items']));
}
I would like to pass variable (that would be service menager) to a build-in helper of zend. Is it possible? To be more clearly:
There is a zend helper called Url, which constructs url's
In this helper I would like to get some data from database, so I need to pass there connection or model (doesn't matter really)
Depends on data get in point 2. I would like to construct my custom link
Well, the thing looks like this: I'm trying to make own custom routing. So in database I have controller, action and it's alias. For example:
Home\Controller\Home | index | myalias
Routing works fine, that means that if I type url:
example.com/myalias
Then Zend will open Home controller and index action. But on whole page I have url's made by Zend build-in Url helper, which looks like this:
$this->url('home', array('action' => 'index'));
So link looks:
example.com/home/index
I would like to change link to
example.com/myalias
without changing links generated by Url helper on whole page. So before helper return url, should check if that url have alias, and if so then should return that alias exept regular url.
In Module.php of the module where you have he helper class file, write the following -
//use statements
class Module {
//public function getAutoloaderConfig() { [...] }
//public function getConfig() { [...] }
public function getViewHelperConfig() {
return array(
'factories' => array(
'Url' => function ($sm) {
$locator = $sm->getServiceLocator();
$viewHelper = new View\Helper\Url;
//passing ServiceLocator to Url.php
$viewHelper->setServiceLocator($locator); //service locator is passed.
return $viewHelper;
},
),
);
}
}
Now in the Url.php, we need a function setServiceLocator() and getServiceLocator().
//use statements
class Url {
public $serviceLocator;
public function getServiceLocator() {
return $this->serviceLocator;
}
public function setServiceLocator($serviceLocator) {
if($this->serviceLocator == null)
$this->serviceLocator = $serviceLocator;
return;
}
}
I hope it helps.
I'm trying to create user profiles for my site where the URL is something like
mysite.com/user/ChrisSalij
Currently my controller looks like so:
<?php
class User extends Controller {
function user(){
parent::Controller();
}
function index(){
$data['username'] = $this->uri->segment(2);
if($data['username'] == FALSE) {
/*load default profile page*/
} else {
/*access the database and get info for $data['username']*/
/*Load profile page with said info*/
}//End of Else
}//End of function
}//End of Class
?>
At the moment I'm getting a 404 error whenever i go to;
mysite.com/user/ChrisSalij
I think this is because it is expecting there to be a method called ChrisSalij.
Though I'm sure I'm misusing the $this->uri->segment(); command too
Any help would be appreciated.
Thanks
It's because the controller is looking for a function called ChrisSalij.
A few ways to solve this:
change
function index(){
$data['username'] = $this->uri->segment(2);
to be
function index($username){
$data['username'] = $username;
and use the URL of mysite.com/user/index/ChrisSalij
if you don't like the idea of the index being in the URL you could change the function to be called a profile or the like, or look into using routing
and use something along the lines of
$route['user/(:any)'] = "user/index/$1";
to correctly map the URL of mysite.com/user/ChrisSalij