I want to know if it is possible to create multiple roots for single methode controller in laravel? something like this :
//route
Route::get('foo/bar', 'FooController#bar');
Route::get('foo/bar/{id}', 'FooController#bar');
Route::get('foo/bar/{id}/{date}', 'FooController#bar');
//controller
class FooController extends Controller {
public function bar($id,$date)
{
//do something
}
}
Yes but you have to handle null parameters, like that:
public function bar($id=null, $date=null)
{
....
But at this point its better to declare e single route with optional parameters:
Route::get('foo/bar/{id?}/{date?}', 'FooController#bar');
Related
I am trying to attach multiple models with one controller using implicit model binding but I am getting the following error if I try to attach more than one model with methods.
index() must be an instance of App\\Http\\Models\\Modelname, string given
Here is my code:
public function index(Model1 $model1,Model2 $model2,Model3 $model3)
{
print_r($application_endpoint);
}
Route:
Route::resource("model1.model2.model3","MyController",["except"=>["create","edit"]]);
Your route should looks like that:
Route::resource("your_route/{model1}/{model2}/{model3}","MyController",[
"except"=>["create","edit"]
]);
Yess you can register routes like these
Route::resource("model1.model2.model3","MyController",["except"=>["create","edit"]]);
but in your controller, you have to
public function index($id,$id2,$id3)
{
print_r($application_endpoint);
}
OR
you can do like this
Route::model('key/key/key', 'MyController')
and in your controller
public function index(Model1 $model1,Model2 $model2,Model3 $model3)
{
print_r($application_endpoint);
}
I feel I repeat myself in Laravel (4) controllers. For example, I need some $variables for every view. I get them from cache or database. Because geting and processing them take some lines of codes (between 5-100 lines), I repeat them in every controller function. This is especially a problem when updating functions (They increase complexity).
How can I avoid this without any negative effect?
Note: $variables are mostly not global variables.
There are many ways to go about this, but it sounds like the variables are more specific to your View's than your controllers.
You can easily share variables across your views in the boot method of your AppServiceProvider.
view()->share('variables', function(){
//you can share whatever you want here and it will be availble in all views.
});
You can create a static helper class (all static functions)
e.g.
class VarHelper {
public static function getVars() {
return [];
}
}
You can create your own basecontroller you extend in every other controller
e.g.
class MyController extends Controller {
public function getVars() {
return [];
}
}
class BlaController extends MyController {
public function doBla() {
$vars = $this->getVars();
}
}
creating the function inside the controller and call it in the other functions
use a Trait
And probably more solutions
Create a trait with a method to set all of the necessary variables.
use View;
trait SharedControllerVariables {
public function loadUsersSubscription() {
View::make('user_subscription_variable_1', [...data...]);
View::make('user_subscription_variable_2', [...data...]);
}
}
Then call it in your controller constructor:
class MyController extends Controller {
use SharedControllerVariables;
public function __construct() {
$this->loadUsersSubscription();
}
}
I have a route with dynamic model recognition. In other words, I take the desired model as an argument and use it in the controller. I have complex authorization in my app and I need to pass the model class name as a variable to the $user->can() method for using policies, but for some reason it doesn't work. Here's my code:
Policy:
public function view($user, Model $model) {
return $user->model_id == $model_id;
}
public function create($user) {
return $user->isAdmin();
}
Controller:
public function createModel($model) {
$model_class = $model . '::class';
if (Auth::user()->can('create', $model_class)) {
return $model_class::create();
}
return 'invalid_permissions';
}
If I hardcode the model class name it works. For example, if my model is 'Car' and in the controller I put:
if (Auth::user()->can('create', Car::class)) {
Anybody got any ideas why this is so and how to fix it? I hope that it's possible because I would have to change my whole concept if it isn't.
*Note: this is example code, not my actuall classes
I would like to have the following url:
http://localhost/question/1/choices/
and optionally /question/1/choices/3
Where 1 is a question_id and 3 is a choice_id.
How can I do that in Laravel?
Thanks
UPDATE
I think I could achieve this with something like
Route::get('questions/(:num)/choices/(:num)')
But how can I link it to the controller
Class Questions extends Base_Controller {
public static $restful = TRUE;
public function get_choices($question_id, $choice_id) {
//
}
}
Do you'll want a Questions_Controller (remember the _Controller, it's important) like this:
// controllers/questions.php
class Questions_Controller extends Base_Controller {
public $restful = true;
public function get_choices($question_id, $choice_id)
{
// Use $question_id and $choice_id
}
}
And your route would look like controller#action, so...
// routes.php
Route::get('questions/(:num)/choices/(:num)', 'questions#choices');
Routing to actions is covered at the end of Controller Routing, just before the section on CLI Route Testing. Wildcards work the same with actions as they do anonymous functions.
Laravel allows you to use nested resources..
In your case you could have the following in your routes.php
Route::resource('question', 'QuestionController');
Route::resource('question.choices', 'ChoicesController');
Then in your ChoicesController be sure to pass in both question_Id and choice_Id
You can check if everything is routed correctly by running:
php artisan routes
I have two controllers a and b.
I would like to call a method of controller a from a method of controller b.
Could anyone help explain how I can achieve this?
This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).
If you want common functionality, you should build a library to be used in the two different controllers.
I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.
You can load into a string by adding true at the end of the view call:
$string_view = $this->load->view('someview', array('data'=>'stuff'), true);
test.php Controller File :
Class Test {
function demo() {
echo "Hello";
}
}
test1.php Controller File :
Class Test1 {
function demo2() {
require('test.php');
$test = new Test();
$test->demo();
}
}
Very simple way in codeigniter to call a method of one controller to other controller
1. Controller A
class A extends CI_Controller {
public function __construct()
{
parent::__construct();
}
function custom_a()
{
}
}
2. Controller B
class B extends CI_Controller {
public function __construct()
{
parent::__construct();
}
function custom_b()
{
require_once(APPPATH.'controllers/a.php'); //include controller
$aObj = new a(); //create object
$aObj->custom_a(); //call function
}
}
I agree that the way to do is to redirect to the new controller in usual cases.
I came across a use case where I needed to display the same page to 2 different kind of users (backend user previewing the page of a frontend user) so in my opinion what I needed was genuinely to call the frontend controller from the backend controller.
I solved the problem by making the frontend method static and wrapping it in another method.
Hope it helps!
//==========
// Frontend
//==========
function profile()
{
//Access check
//Get profile id
$id = get_user_id();
return self::_profile($id);
}
static function _profile($id)
{
$CI = &get_instance();
//Prepare page
//Load view
}
//==========
// Backend
//==========
function preview_profile($id)
{
$this->load->file('controllers/frontend.php', false);
Frontend::_profile($id);
}
I posted a somewhat similar question a while back, but regarding a model on CI.
Returning two separate query results within a model function
Although your question is not exactly the same, I believe the solution follows the same principle: if you're proposing to do what you mention in your question, there may be something wrong in the way you're coding and some refactoring could be in order.
The take home message is that what you're asking is not the way to go when working with MVC.
The best practice is to either use a Model to place reusable functions and call them in a controller that outputs the data through a view -- or even better use helpers or libraries (for functions that may be needed repeatedly).
You can do like
$result= file_get_contents(site_url('[ADDRESS TO CONTROLLER FUNCTION]'));
Replace [ADDRESS TO CONTROLLER FUNCTION] by the way we use in site_url();
You need to echo output in controller function instead of return.
You can use the redirect() function.
Like this
class ControllerA extends CI_Controller{
public function MethodA(){
redirect("ControllerB/MethodB");
}
}
Controller to be extended
require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');
$report= new onlineAssessmentReport();
echo ($report->detailView());
You can use the redirect URL to controller:
Class Ctrlr1 extends CI_Controller{
public void my_fct1(){
redirect('Ctrlr2 /my_fct2', 'refresh');
}
}
Class Ctrlr2 extends CI_Controller{
public void my_fct2(){
$this->load->view('view1');
}
}
very simple
in first controllr call
$this->load->model('MyController');
$this->MyController->test();
place file MyController.php to /model patch
MyController.php should be contain
class MyController extends CI_Model {
function __construct() {
parent::__construct();
}
function test()
{
echo 'OK';
}
}