Define base url for laravel - php

I am new to laravel. My url for my only controller is
http://localhost/myapp/public/users
In the views for the form functions, I don't want to have to do an absolute path to the post function, e.g.
<form method='post' action='/myapp/public/user/update-user'>
I want to just set the users controller as the base url path so I can say in my form
<form method='post' action='/update-user'>
Is this possible?

Use URL::to()
or simply use laravel form
{{Form::open(array('url'=>'route_name'))}}

You can use URL::to() function.Laravel supports RESTful API or RESTful routing. So it is not a good idea to use routing like this.So use like,
In app/routes.php
// for view (GET)
Route::get('users', function(){
View::make('users');
});
Route::post('users', function(){
// do form validation and process here or call a function from controller
});
Then in your form use,
echo Form::open();
// form elements
echo Form::close();

Yes, it is possible, but it's a little complicated because laravel isn't really set up to support this.
You need to change the file vendor/laravel/framework/src/Illuminate/Http/Request.php, replacing the function root() with this:
public function root($domain = NULL)
{
return rtrim(($domain?:$this->getSchemeAndHttpHost()).$this->getBaseUrl(), '/');
}
And then in the getRootUrl($scheme, $root = null) method in the file vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php you need to change this line:
$root = $root ?: $this->request->root();
to this:
$root = $this->request->root($root);
That should allow laravel to automatically detect and handle subfolders correctly, so you will be able to use the standard URL methods.

First, you need to hide the /public/ part of your URL using the virtual host or the alias in your web server (apache or ...). The entry point (http://some.host/alias/ or http://some.virtual.host/) should lead directly to the public folder (i.e. /whatever/path/myapp/public/).
Second, using the routes, you can do the remaining easily. The route
Route::get('update_users', "UsersController#updateAction")
will redirect the http://whatever.host/update_users to the correct action without the need of the ugly format.

Related

How to achieve this kind of url routing in codeigniter

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';

Laravel routing and route parameters

I have route defined in my route.php file like below:
Route::get('{test1}/{test2}/{test3}', function($test1, $test2, $test3) {
$result = [$test1, $test2, $test3];
return view('view', compact('result'));
});
it works fine in my controller but on the view part when i see it in the browser when i just write something like this in browser:
http://localhost/mysitefolder/public/test1/test2/test3
it loads the view and pass all the data but it gets all of my assets like my stylesheets, images and scripts from a url like below:
http://localhost/mysitefolder/public/test1/test2/js/jquery.js
why is that happing?
thanks in advance!
Two solutions either use a / in the start of your URLs so that relative addressing is not used or use laravel's helper functions {{ asset('/js/script.js') }}.
When you do not use '/' in the beginning your url, it is treated as if it was a relative address and current location is added in its start.
Sometimes even '/' won't work if your application is not served on Root level. For example you have your application at http://localhost/yourapplication then / would refer to your localhost instead of application, that's why best way is to use laravel's helper function.

Laravel3: How can I forward post methods to action of controller?

Route::get('admin/user/add', function()
{
if (!Input::has('submit'))
return View::make('theme-admin.user_add');
else
Redirect::to('admin#user_add_process');
});
Normal GET request to admin/user/add shows the register form. However, when the form is submitted, I have to redirect it to action_user_add_process() function of Admin controller so I can save values to database.
The solution above doesn't work and I get 404's.
I call form action like this:
action="{{ URL::to('admin/user/add') }}">
How can I solve this issue?
Ps. If there is a shorter way to achieve this, let me know!
You need to specify that you are redirecting to a controller action using the to_action() method of Redirect.
return Redirect::to_action('admin#user_add_process');
Alternatively, you could just use this URL that doesnt even use the route you created making the if/else irrelevant.
{{ URL::to_action('admin#user_add_process') }}
On a third note, keeping your routes clean makes maintainence alot easier moving forward. As routes use a restful approach, take advantage of it. Using the same URL you can create and return the View with a GET request and submit forms with a POST request.
Route::get('admin/user/add', function() { ... }
Route::post('admin/user/add', function() { ... }
You can also have your routes automatically use a controller action like this:
Route::post('admin/user/add', 'admin#user_add_process');

MVC form data submission to controller

I am managing to deploy a very simple implementation, containing a registration form and for demonstration purposes, I have chosen to use the MVC pattern.
My slight issue is that when I press the submit button, I want the submitted data to be handled by the suitable method of the controller.
For instance:
within the view part, I declare the form like this :
<form action="controller/validate" method="post"/>
I am assuming that this is a routing-related thing, but I am curious whether another way can be suggested.
--
Regards,
Theo
A router can be as simple as a switch statement instead of a full blown router for the small sites:
switch($_SERVER['REQUEST_URI']) {
case 'controller/validate':
$view = new \Views\User\Registration();
$controller = new \Controllers\UserRegistration($view);
$method = 'validate';
break;
default:
$view = new \Views\Error\NotFound();
$controller = new \Controllers\Error($view);
$method = 'notFound';
break;
}
echo $controller->$method();
Also note that instead of doing a relative URL based on the current path you often really want to do a relative URL to the document root:
<form action="/controller/validate" method="post"/>
Note the leading slash.
The above is just a simple (untested) example of semi pseudocode
Usually, you would make your controller accessible through a route (like POST /register). A controller action is assigned to this route in a bootstrap file. Some pseudo-code:
$framework->route('GET', '/register',
'RegistrationController::action_form');
$framework->route('POST', '/register',
'RegistrationController::action_submit');
Another aproach would be mapping routes directly to controllers (some frameworks do this, I believe Kohana is one of them) like this:
Route: /register/submit
Resolves to: RegisterContoller::action_submit()
Management of request method (GET, POST, PUT, DELETE in standard HTTP) happens in the action methods.

custom URL mappings in codeigniter like redmine?

So redmine has a very peculiar url mapping style that i observed :
http://demo.redmine.org/projects/<project-name>/controller/action
samples :
http://demo.redmine.org/projects/produto/activity
http://demo.redmine.org/projects/produto/issues/new
http://demo.redmine.org/projects/produto/issues/gantt
http://demo.redmine.org/projects/produto/files
and the url changes as the project changes.
how do i do this in codeigniter ? I'm thinking it can be done with routes.php but so far i'm not able to get anywhere.
Looking for any help. Thanks.
Use the following function inside your "application/controllers/projects.php" controller:
public function _remap($method)
{
if ($method == 'project-name')
{
//display project1
}
elseif($method == 'project-name2')
{
//display project2
}
}
You can do the same for varying methods by extracting them from database
take a look here:
http://codeigniter.com/user_guide/general/controllers.html#remapping
you can also route your controller by using custom routes in application/config/routes.php
$route['example'] = "controller/function";
$route['example2/(:any)'] = "controller/function";
You use the routes file in application/config/routes.php
You would use something like this:
// the $1 maps to :any
$route['projects/produto/:any'] = "$1";
// the $1 maps to the first any, $2 maps to the second :any
$route['projects/produto/:any/:any'] = "$1/$2";
You will want mod_rewrite enabled if you are handling clean URL's. Otherwise expect the index.php/controller/action. I cant test it myself there, but you should refer to:
Once you add a route (It has to be called $route[] inside the configuration), refresh the page and try to go to the URL!
http://codeigniter.com/user_guide/general/routing.html
add this to your routes.php (btw: you need url-rewriting enabled for routes to work, ie. using .htaccess)
$route['projects/(:any)/(:any)/(:any)'] = "$2/$3/$1";
for example /projects/produto/issues/new will call the function new in the class issues and pass it the parameter 'produto'
also check http://codeigniter.com/user_guide/general/routing.html

Categories