I want to create dynamic pages CMS for my Laravel app. Admin is allowed to provide any URI for any page, so for example, he can create page with one/two/three URI and http://example.com/one/two/three will point to this site. I already figured out it's possible to add single route for multiple level URLs like this:
get('{uri}', 'PageController#view')->where('uri', '.+');
Now, I also want to have /{username} URLs to point to users profiles. That means, if I need to make it work together. For me, the perfect code would be something like this:
get('{username}', 'ProfileController#view');
get('{uri}', 'PageController#view')->where('uri', '.+');
Then, in ProfileController I'd like to make my route go further just like it wasn't there. Something like this:
// ProfileController
public function view()
{
$user = User::whereUsername($username)->first();
if ($user === null) {
// Go to the next route.
}
}
Can it be done with Laravel?
I can think of another solution, just to have dynamic routing controller for both usernames and page uris mapping, but I would prefer to have it as separate routes.
You can resolve a new PageController instance out of the Service Container if $user is null.
// ProfileController
public function view()
{
$user = User::whereUsername($username)->first();
if ($user === null) {
// Go to the next route.
$params = []; // If your view method on the PageController has any parameters, define them here
$pageController = app(PageController::class);
return $pageController->callAction('view', $params)
}
}
This way, the {username} route will stay but will show custom content defined by the admin.
Edit:
If you don't want to call a controller manually, you could analyze the current URL segments and check for an existing user before you define your route. In order to not make your routes.php file too complex, I'd add a dedicated service class that analyzes your URL segments:
App\Services\RouteService.php:
<?php
namespace App\Services;
class RouteService {
public static function isUserRoute()
{
if(count(Request::segments()) == 1)
return !! User::whereUsername(Request::segment(1))->first();
}
return false;
}
}
routes.php:
<?php
use App\Services\RouteService;
if(RouteService::isUserRoute())
{
get('{username}', 'ProfileController#view');
}
get('{uri}', 'PageController#view')->where('uri', '.+');
I have not tested this, but it should work. Adjust the RouteService class to your needs.
I'm using the first approach in my CMS and it works realy well. The only difference is that I have written a Job that handles all incoming requests and calls the controller actions respectively.
Related
I want to use route localization like said here https://codeigniter.com/user_guide/outgoing/localization.html#in-routes
So I need to add route rule like:
$routes->get('{locale}/books', 'App\Books::index');
But I want to make this rule for all controllers - not to specify rules for all controllers. So I added the rule:
$routes->add('{locale}/(:segment)(:any)', '$1::$2');
I have controller Login with method index(). When I go to mydomain.com/Login method index() is loaded successfull. But when I go to mydomain.com/en/Login (as I expect to use my route) I got 404 Error with message - "Controller or its method is not found: \App\Controllers$1::index". But locale is defined and set correctly.
If I change my route to $routes->add('{locale}/(:segment)(:any)', 'Login::$2'); then mydomain.com/en/Login is loaded successfull as I want. But in this way I have to set routes for every controller and I want to set one route to work with all controllers.
Is it possible to set route with setting of dynamic controller name?
I'm not sure it is possible directly, but here is a workaround:
$routes->add('{locale}/(:segment)/(:any)', 'Rerouter::reroute/$1/$2');
Then, your Rerouter classlooks like this:
<?php namespace App\Controllers;
class Rerouter extends BaseController
{
public function reroute($controllerName, ...$data)
{
$className = str_replace('-', '', ucwords($controllerName)); // This changes 'some-controller' into 'SomeController'.
$controller = new $className();
if (0 == count($data))
{
return $controller->index(); // replace with your default method
}
$method = array_shift($data);
return $controller->{$method}(...$data);
}
}
For example, /en/user/show/john-doe will call the controller User::show('john-doe').
i want to achieve url routing something like www.example.com/alicia
suppose alicia is not a class name or method name just something like passing data in url and with some class i want to access this and want to use it for further process.How i can use it ? Thanks in advance.
You can use Codeigniter's built-in routing, the file route.php is located in your config folder.
there you can add:
$route['alicia'] = 'welcome/index/something';
$route['alicia/:any'] = 'welcome/index/someotherthing/$1';
then in your controller, for example welcome you just create a function like:
public function index($page = null){
if($page=='something'){
// do what you need to do, for example load a view:
$this->load->view('allaboutalicia');
}
elseif ($page=='someotherthing'){
// here you can read in data from url (www.example.com/alicia/2017
$year=$this->uri->segment(2); // you need to load the helper url previously
}else{
// do some other stuff
}
}
documentation on routing and on urlhelper
edit after comment:
in case your uri segment is representing a variable, like a username, then you should use a uri scheme like www.example.com/user/alice and create your route like:
$route['user/:any'] = 'welcome/index/user';
then in your controller welcome
public function index($page=null){
if($page=='user'){
// do what you need to do with that user
$user=$this->uri->segment(2); // you need to load the helper url
}
else{
// exception
}
}
This could be tricky because you don't want to break any existing urls that already work.
If you are using Apache, you can set up a mod_rewrite rule that takes care to exclude each of your controllers that is NOT some name.
Alternatively, you could create a remap method in your base controller.
class Welcome extends CI_Controller
{
public function _remap($method)
{
echo "request for $method being handled by " . __METHOD__;
}
}
You could write logic in that method to examine the requested $method or perhaps look at $_SERVER["REQUEST_URI"] to decide what you want to do. This can be a bit tricky to sort out but is probably a good way to get started.
Another possibility, if you can think of some way to distinguish these urls from your other urls, would be to use the routing functionality of codeigniter and define a pattern matching rule in the routes.php file that points these names to some controller which handles them.
I believe that the default_controller will be a factor in this. Any controller/method situations that actually correspond to a controller::method class should be handled by that controller::method. Any that do not match will, I believe, be assigned to your default_controller:
$route['default_controller'] = 'welcome';
I want to add a functionality on my web app where users visit the same URL and get different pages depending if they are logged in or not. The way I'm doing this now is using a middleware to redirect logged in users to /home. But, I want to do something like facebook does..
When someone types http://facebook.com, it analyzes if the person is logged in, if they are, it shows their home, if they are not, it shows the registration page on the same URL (you can see that the address in the bar does not change)
I'm trying to use this code on my route:
Route::get('/', array('as'=>'home', 'uses'=> (Auth::check()) ? "usercontroller#home" : "homecontroller#index" ));
Found Here: https://stackoverflow.com/a/18896113/2724978
But it just shows the second controller method ("homecontroller#index") no matter if the user is logged in or not.
Is it just me or can't you just do as #AJReading has suggested and use an ordinary controller method to handle this?
Set up like so:
In your HomeController.php:
class HomeController extends Controller
{
/**
* Show a different view depending on whether or not the user is logged-in.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (Auth::check()) {
// logged-in
return view('home.index.authorised')->with('user', Auth::user());
} else {
// not logged-in
return view('home.index.guest');
}
}
}
Then create your alternate views e.g. resources/views/home/guest.blade.php
here is exactly what you want:
Route::get('/', function() {
$guest = Auth::guest();
if($guest)
{
$controller = $this->app->make('App\Http\Controllers\TaskController');
return $controller->callAction('guest', $parameters = array());
}
else
{
$controller = $this->app->make('App\Http\Controllers\TaskController');
return $controller->callAction('user', $parameters = array());
}
});
Just replace the names with yours.
Tested on: Laravel Framework version 5.1.35 (LTS).
Should be improved further by looking at the namespacing.
Did came up with a better solution using middleware - but didn't save it and can't recreate it now.
Answer derived from/based on:
Laravel single route point to different controller depending on slugs
http://laravel.io/forum/10-16-2014-l5-controller-does-not-exist
I have a Controller witch contains more than 150 functions. almost all of the functions inside the controller are returning views.
each view should change if the user is logged in.
I almost handled this in the view side by using parent blades and etc. But in the controller side for almost every function i should check if the user is logged in and return some specific data about the user along with the view.
for example:
$user=[];
if(Auth::check())
{
$user=Auth::user;
$reputation=$user['reputation'];
$messages=$user->messages();
$notifications=$user->notification();
}
return view('pages.profile')->with(['user'=>$user , 'messages'=>$messages , 'notifications'=>$notifications]);
I thought that this is possible using middlewares but i could not figure it out.
what are the alternatives here?
for more information i am using laravel 5.
One solution could be using your custom function instead of view(). Sth like:
//in your controller action
public function someAction() {
return $this->view('pages.profile');
}
protected function view($template, $data = array()) {
return view($template)->with($data)->with([data that needs to be passed to all views]);
}
I have created a fully functional CakePHP web application. Now, i wanna get it to the next level and make my app more "opened". Thus i want to create an RESTful API. In the CakePHP docs,i found this link (http://book.cakephp.org/2.0/en/development/rest.html) which describes the way to make your app RESTful. I added in the routes.php the the two lines needed,as noted at the top of the link,and now i want to test it.
I have an UsersController.php controller,where there is a function add(),which adds new users to databases. But when i try to browse under mydomain.com/users.json (even with HTTP POST),this returns me the webpage,and not a json formatted page,as i was expecting .
Now i think that i have done something wrong or i have not understood something correctly. What's actually happening,can you help me a bit around here?
Thank you in advace!
You need to parse JSON extensions. So in your routes.php file add:
Router::parseExtensions('json');
So a URL like http://example.com/news/index you can now access like http://example.com/news/index.json.
To actually return JSON though, you need to amend your controller methods. You need to set a _serialize key in your action, so your news controller could look like this:
<?php
class NewsController extends AppController {
public function index() {
$news = $this->paginate('News');
$this->set('news', $news);
$this->set('_serialize', array('news'));
}
}
That’s the basics. For POST requests, you’ll want to use the RequestHandler component. Add it to your controller:
<?php
class NewsController extends AppController {
public $components = array(
'RequestHandler',
...
);
And then you can check if an incoming request used the .json file extension:
public function add() {
if ($this->RequestHandler->extension == 'json') {
// JSON request
} else {
// do things as normal
}
}