CI Basic Routing - codeigniter

I have a route in my route.php :
$route['admin/(:any)'] = 'ix/$1';
It routes URI such as localhost/somename/admin/home to localhost/somename/ix/home.php controller.
The problem is if the URI is like this : localhost/somename/admin/blog/updates (nonexistant function), rather than returning 404, it will just run the blog controller construct code.
How do I avoid this? One option is to add the routing to accept only necessary parameters, but is there any other way?
Thanks

You can add a remap function to route the controller internally:
http://ellislab.com/codeigniter/user_guide/general/controllers.html#remapping
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
show_404();
}

Related

Authorization isn’t executed in laravel

This is form ‘login’, when I’m enter information in input and after press button ‘login’ I move to page with audit where 0 is authorization isn't executed and 1 is authorization is executed. I'm trying to create authorization in laravel.
I did it in other project in order to understand how it works and then all was good. Now I'm trying to transfer it in my main project but when I am logging in nothing work.
I don't have any mistake, authorization is simply not executed. I will grateful for any help.
Registration function
public function sub(ContactSignup $request){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
$contact = new SignUps();
$contact->name = $request->name;
$contact->surname = $request->surname;
$contact->age = $request->age;
$contact->password = bcrypt($request->password);
$contact->email = $request->email;
$contact->save();
Auth::login($contact);
if($contact){
Auth::login($contact);
return redirect(route('user.sign-up'))->with('success', 'Реєстрація пройшла успішно');
}
}
Function login
public function subin(ContactSignin $request){
if(Auth::check()){
return redirect()->intended(route('user.mainpage'));
}
$contact = $request->only(['email', 'password']);
if(Auth::attempt($contact)) {
dd(1);
}
else {
dd(0);
}
return redirect()->intended(route('user.mainpage'));
}
Web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return redirect()->route('mainpage');
});
Route::name('user.')->group(function(){
Route::view('mainpage', 'mainpage')->middleware('auth')->name('mainpage');
Route::get('/signin', function(){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
return view('signin');
})->name('sign-in');
Route::post('/signin', [\App\Http\Controllers\ContactController::class, 'subin'])->name('sign-in');
Route::get('logout', function(){
Auth::logout();
return redirect('/');
})->name('logout');
Route::get('/signup', function(){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
return view('signup');
})->name('sign-up');
Route::post('/signup', [\App\Http\Controllers\ContactController::class, 'sub'])->name('sign-up');
});
Route::get('/mainpage', function () {
return view('mainpage');
})->name('mainpage');
in your methods inside your controller you have form request class called ContactSignin
in this class you have code
public function authorize()
{
return false;
}
make it true
The form request class is responsible of validating your request ,
also contains an authorize method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource
since you handle authorization logic for the request in the routes by provide
middleware('auth') it is no need to check for use authentication in your form request class
first you don't have route named ('user.mainpage') you have to define it in web.php
second , since you named your rout in
Route::get('/mainpage', function () {
return view('mainpage');
})->name('mainpage');
, you must redirect to the name of the route not to the path
for example if your route is ('/api/main')->name('main') , you have to put the rout name in the redirect method , for example redirect(route('main'));

How to use parameter from function to create an URL? Laravel Routing

I'm sending an URL hashed and when i get it i have to show a view on Laravel, so i have those functions on the controller and also some routes:
This are my routes:
Route::post('/sendLink', 'Payment\PaymentController#getPaymentLink');
Route::get('/payment?hash={link}', 'Payment\PaymentController#show');
And this are the functions i have on my controller:
public function getPaymentLink (Request $request){
$budgetId = $request['url.com/payment/payment?hash'];
$link = Crypt::decryptString($budgetId);
Log::debug($link);
//here to the show view i wanna send the link with the id hashed, thats why i dont call show($link)
$view = $this->show($budgetId);
}
public function show($link) {
$config = [
'base_uri' => config('payment.base_uri'), ];
$client = new Client($config);
$banking_entity = $client->get('url')->getBody()->getContents();
$array = json_decode($banking_entity, true);
return view('payment.payment-data')->with('banking_entity', $array);
}
And this is getting a "Page not found" message error.
What i want to to is that when i the client clicks on the link i send him that has this format "url.com/payment/payment?hash=fjadshkfjahsdkfhasdkjha", trigger the getPaymentLink function so i can get de decrypt from that hash and also show him the view .
there is no need to ?hash={link} in get route
it's query params and it will received with $request
like:
$request->hash
// or
$request->get('hash')
You need to define route like this:
Route::get('/payment/{hash}', 'Payment\PaymentController#show');
You can now simply use it in your Controller method like below:
<?php
public function getPaymentLink (Request $request,$hash){
$budgetId = $hash;
// further code goes here
}

Laravel Ajax controller with single route

Just wondering if this is a good way to write ajax code to interact with Laravel routes?
Example my application's require to list all customer data and also list all country through ajax. I have 3 controller ApiController, CustomerController, CountryController.
So in my routes.php I have this routes
Route::get('api/v1/ajax/json/{class}/{function}', 'Api\v1\ApiController#ajaxreturnjson');
In the ApiController.php, I have below function to call other controller function to return the data I need.
class ApiController extends Controller
{
public function ajaxreturnjson(Request $request, $controller, $function){
$input = $request->input();
if($request->input('namespace') != ''){
$namespace = $request->input('namespace');
unset($input['namespace']);
}else{
$namespace = 'App\Http\Controllers';
}
$data = array();
try {
$app = app();
$controller = $app->make($namespace.'\\'.$controller);
$data = $controller->callAction($function, array($request)+$input);
} catch(\ReflectionException $e){
$data['error'] = $e->getMessage();
}
return response()->json($data);
}
}
So example to use the ajax, I just need to pass the class name, namespace and also the function name to the ajax url.
Example to retrieve all customer info.
$.ajax({
dataType:"json",
url:"api/v1/ajax/json/CustomerController/getList",
data:"namespace=\\App\\Http\\Controllers\\",
success:function(data){
}
})
So in this way, I don't have to create so many routes for different ajax request.
But I am not sure if this will cause any security issue or is this a bad design?
Personally, I would not do it this way. Sure, you could do it this way, but it's not very semantic and debugging it could be a pain.
Also, if someone else begins working on the project, when they look at your routes file, they won't have any idea how your app is structured or where to go to find things.
I think it's better to have a controller for each Thing.

Obtain CodeIgniter links that consider routes.php

How can I link pages in my site considering routes.php?
Example:
$route['login'] = 'user/login';
The code above allows me to see "user/login" visiting just "login". But how can I link to that page using the internal route (user/login) and get as a result the "external route" "login".
I think it's important because I could change my URLs just modifiying "routes.php" and linking everything with internal routes.
From a Drupal perspective I can have my internal route "node/1" and the external url could be "about-us". So if I use "l('node/1')" this will return "about-us". Is there a function like "drupal_get_path_alias"?
Right now I can't find anything in the CI docs that point me to the right direction.
Thanks for your help.
You could have a look at using something like
http://osvaldas.info/smart-database-driven-routing-in-codeigniter
This would allow you to have the routes configured in the database. Then if you want to dynamically create you links through a model like this:
class AppRoutesModel extends CI_Model
{
public function getUrl($controller)
{
$this->db->select('slug');
$this->db->from('app_routes');
$this->db->where('controller', $controller);
$query = $this->db->result();
$data = $query->row();
$this->load->library('url');
return base_url($data->slug);
}
public function getController($slug)
{
$this->db->select('controller');
$this->db->from('app_routes');
$this->db->where('slug', $slug);
$query = $this->db->result();
$data = $query->row();
return $data->controller;
}
}
These have not been fully tested but will hopefully give you the general idea.
I hope this helps you :)
Edit------------------------------
You can create a routes_helper.php and add a function like
//application/helpers/routes_helper.php
function get_route($path)
{
require __DIR__ . '/../config/routes.php';
foreach ($route as $key => $controller) {
if ($path == $controller) {
return $key;
}
}
return false;
}
$this->load->helper('routes');
echo get_route('controller/method');
This does roughly what you want although this method does not support the $1 $2 etc vars that can be added to reflect the :num or :any wildcard that exist. You can edit the function to add that functionality but this will point you in the right direction :D
You can do that with .htaccess file:
Redirect 301 /user/login http://www.example.com/login

Laravel 4 : Route to localhost/controller/action

I'm more or less new to Laravel 4. I've never used routes before but normally what I'm used to is url/controller/action and then the backend routing for me. I've read the documentation for routes and controllers a few times as well as read through some tutorials and so, I'm trying to figure out how to get this to work without writing a route for every controller and action.
I tried something like
Route::get('{controller}/{action}', function($controller, $action = 'index'){
return $controller."#".$action;
});
Now then, I know this is wrong since it doesn't work, but what am I missing? On most tutorials and stuff I'm seeing an route for more or less every controller and action like:
Route::get('/controller/action' , 'ControllerName#Action');
Which seems silly and like a waste of time to me.
Is there anyway to achieve what I want?
If you are looking for a more automated routing, this would be the Laravel 4 way:
Route:
Route::controller('users', 'UsersController');
Controller (in this case UsersController.php):
public function getIndex()
{
// routed from GET request to /users
}
public function getProfile()
{
// routed from GET request to /users/profile
}
public function postProfile()
{
// routed from POST request to /users/profile
}
public function getPosts($id)
{
// routed from GET request to: /users/posts/42
}
As The Shift Exchange mentioned, there are some benefits to doing it the verbose way. In addition to the excellent article he linked, you can create a name for each route, for example:
Route::get("users", array(
"as"=>"dashboard",
"uses"=>"UsersController#getIndex"
));
Then when creating urls in your application, use a helper to generate a link to a named route:
$url = URL::route('dashboard');
Links are then future proofed from changes to controllers/actions.
You can also generate links directly to actions which would still work with automatic routing.
$url = URL::action('UsersController#getIndex');
app\
controllers\
Admin\
AdminController.php
IndexController.php
Route::get('/admin/{controller?}/{action?}', function($controller='Index', $action='index'){
$controller = ucfirst($controller);
$action = $action . 'Action';
return App::make("Admin\\{$controller}Controller")->$action();
});
Route::get('/{controller?}/{action?}', function($controller='Index', $action='index'){
$controller = ucfirst($controller);
$action = $action . 'Action';
return App::make("{$controller}Controller")->$action();
});
I come from .Net world and routing is typically done:
/{Controller}/{action}/{id}
Which looks like:
/Products/Show/1 OR /Products/Show/Beverages
In Laravel I accomplish this routing like so:
Route::get('/{controller?}/{action?}/{id?}', function ($controller='Home', $action='index', $id = null) {
$controller = ucfirst($controller);
return APP::make("{$controller}Controller")->$action($id);
});
The controller would look roughly like so:
class ProductsController extends BaseController {
public function Show($id) {
$products = array( 1 => array("Price" => "$600","Item" => "iPhone 6"),
2 => array("Price" => "$700", "Item" => "iPhone 6 Plus") );
if ($id == null) {
echo $products[1]["Item"];
} else {
echo $products[$id]["Item"];
}
}
}

Resources