Create a route that has uri-segment - codeigniter

I tried to call a function on the controller and the function I have created a route, but how to create a route that has uri-> segement ?
Example
$route['select-item'] = 'select_item';
Controllers
function select_item() {
$item = $this->uri->segment(3);
$data = array ('get_item' => $this->Model->My_item($item));
$this->load->view('Myview');
}
Views
<?php echo $row->item;?>

I suggest you use codeigniters wildcards on routes, You can go ahead and set your route to:
$route['select-item/(:any)'] = 'select_item/$1';
then on your controller, just do:
function select_item($item) {
$data = array ('get_item' => $this->Model->My_item($item));
$this->load->view('Myview',$data);
}
And the link in your view should work properly.

Related

Laravel 6.2 - Dynamically Call a Controller action

I have used a code from Internet to call controller action dynamically. Here is the code for that, and is used in web.php. But I dont fully understand what it does.
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Can someone explain?
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
The first line looks at the request to see whether it is a get or post request, if it is some other types of request that means it does not match and will not proceed further. Then the url are separated into 4 parts corresponding by their name and passed into variables with the same name i.e. $controller, $action, $param1 and $params2 where the last 3 variables do not need to be present (with ? at the end of the name).
$params = explode('/', $params1);
$params[1] = $params2;
I believe this is a crude way to create an array of parameters as $params where the following would be more appropriate.
$params = [$params1, $params2];
.
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
Then load the relevant controller.
return $controller->callAction($action, $params);
And run the corresponding action and passing all the parameters with it.
Hope this makes sense.
This is example of use it:
If you have controller like bellow:
class AdminController extends Controller {
public function index(){ //sample 0, sample 1
...
}
public function view($param1){ //sample2 , sample3
...
}
}
There is some sample route for calling them
sample0: yoursite.com/admin
sample1: yoursite.com/admin/index
sample2: yoursite.com/admin/view
sample3: yoursite.com/admin/view/5
Notice in your question ? in {action?} means it can either have value or not. Other things is simple and clear. Do you need more explaination?

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
}

It can not find my variable in my view in laravel 5.6

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$datanews['newss'] = News::orderBy('created_at','desc')->get();
$dataevent['events'] = Event::orderBy('created_at','desc')->get();
$user['users'] = User::all();
return view('user/aktuelles.index',$datanews, $dataevent,$user);
}
this is a part of my controller, i can show news and events in my view but everytime it says it can not find the variable user?
i dont know why because i dont know why it shows me the other variables but not the user variable???
in my view i can see the other variables like this:
#foreach ($newss as $news)
{{$news->newstitel}}
#endforeach
but i want to show user like this:
{{$user[1]->avatar}}
i tried everything so i tried so look my controller like this:
$user = DB::table('users')->get();
or get the variable via compact
and i tried exactly the same so like this
$user['users'] = User::orderBy('created_at','desc')->get();
and a foreach in my view but it can not found the variable user??
i dont know why
this is the error
Undefined variable: users
return view('user.aktuelles.index', compact('datanews', 'dataevent', 'user');
I am not sure how the helper view() handles the 4th parameter you are passing. According to the docs you can pass data like this:
return view('user/aktuelles.index',[
'datanews' => $datanews,
'dataevent' => $dataevent,
'user' => $user,
]);
or
return view('user/aktuelles.index')->with([
'datanews' => $datanews,
'dataevent' => $dataevent,
'user' => $user,
]);
Maybe give this way a try.
Edit:
The view() helper accepts 3 Parameters: $view = null, $data = [], $mergeData = [] so the 4th parameter you are trying to pass is not even working. You have to pass your data as second parameter or with the chained function with(array $data).
You have to return value in view like below method:
Change this line
$user['users'] = User::orderBy('created_at','desc')->get();
To
$user = User::orderBy('created_at','desc')->get();
return view('user/aktuelles.index', ['datanews' => $datanews,'dataevent'=> $dataevent,'users'=>$user]);
Now, You will get result inside your view using 'users'.
You are not passing variables to view correctly use with or compact to pass variables to view.
i prefer compact as it is simple and easier.
Passing data to view using compact:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$datanews = News::orderBy('created_at','desc')->get();
$dataevent = Event::orderBy('created_at','desc')->get();
$user = User::all();
return view('user.aktuelles.index',compact('datanews', 'dataevent','user'));
}
Passing variables to view using with:
public function index()
{
$datanews = News::orderBy('created_at','desc')->get();
$dataevent = Event::orderBy('created_at','desc')->get();
$user = User::all();
return view('user.aktuelles.index)->with(['datanews' => $datanews,'dataevent'=> $dataevent,'users'=>$user]);
}
You should try this:
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$data['news'] = News::orderBy('created_at','desc')->get();
$data['events'] = Event::orderBy('created_at','desc')->get();
$data['users'] = User::all();
return view('user/aktuelles.index', $data);
}

How to use session_data in codeigniter throughout Website without including in particular view

Is there any other best way to use session_data in website.
How i set session in my project:
$sess_array = array('id' => $row->user_id,'name'=>$row->user_name,'email'=>$row->email,'condition'=>'','balance'=>$row->balance,'did_alloted'=>$row->did_alloted,'create_date'=>$row->create_date);
$this->session->set_userdata('logged_in', $sess_array);
when it comes to controller:
$data['id'] = $session_data['id'];
$data['name'] = $session_data['name'];
$data['email'] = $session_data['email'];
$data['balance']=$session_data['balance'];
$data['did_alloted']=$session_data['did_alloted'];
$data['create_date']=$session_data['create_date'];
$this->load->view('san-reception', $data);
and in my view. I use <?php echo $name ?> to get session_data.
So is there any method by which i can directly access session_data in view without including as $data.
$this->session->userdata('logged_in'); will be available directly in views and hence you just need to assigned this to a variable and then use that as array like bellow.
$userdata=$this->session->userdata('logged_in');
now variable $userdata contain all array field that you set in controller and hence you can use it as $userdata['id'], $userdata['name'] etc
public function __construct()
{
parent::__construct();
$data['session_data']=$this->session->user_data('logged_in');
}
public function some_function(){
$data['dummy']="";
$this->load->view('someview3',$data)
}
public function some_function1(){
$data['dummy']="";
$this->load->view('someview1',$data)
}
public function some_function2(){
$data['dummy']="";
$this->load->view('someview2',$data)
}
If you assign that into the constructor then it will call by automatically whenever a function calls in the controller.
you can view it in you view page by,
print_r($session_data);

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