how to call a methode from model in a controller - php

I know how to call a method in model from controller but I am wondering how to call a method in controller from a model.
$this->load->model('dataOperateModel');
$this->dataOperateModel->saveData($formtype);
this loads a method in model. But I haven't seen anyone do the model to controller.
Is there any easy way to handle this.

You are not suppose to call a Controller actions from a Model. That defeats the point of data separation. I'd advise changing your question to be more specific to the problem that calling the action would solve.
To answer the question. Assuming the controller is called Posts.
//Import controller
App::import('Controller', 'Posts');
//Instantiation
$Posts = new PostsController;
//Load model, components...
$Posts->constructClasses();
//Call a method on the controller.
$Posts->index();

Please chang this:
$this->load->model('dataOperateModel','dataOperate');
$this->dataOperate->saveData($formtype);

Related

Laravel , how to call a function from another controller

I have a controller with the "getUsers" function in a controller called "UserController" , and inside it I want to call a function of the "CarController" controller called "getCars", the two options I have are:
a) Make the second call as "static" , then I can call it without instantiating the class
b) Do not do that function of the static class and I call it in this way
$ car_id = 100;
$ userController = new UserController ();
$ userController-> getCars ($ car_id);
I do not know which is the best practice, or what pros or cons has one or another.
I'm using laravel.
Thanxs.
It is a bad practice to call a controller from another controller, this usually signals that you have badly designed your code and you should think of a different way to achieve what you want.
None the less, you can do it like this:
app()->call('App\Http\Controllers\CarController#getCars');
If your controller method has parameters you can pass them as the second argument:
app()->call('App\Http\Controllers\CarController#getCars', [$param1, $param2]);
To answer your question, you should not call one controller method from another. As #elfu mentioned, this is not the intended functionality of a controller anyway. His post is correct and in your case you should probably use the User model as the location of this method, but I thought I'd at to it a little.
If you do want to share methods between multiple controllers, a good place to do this is through a Trait. In some cases, you are not referencing a model that is shared between controllers, and a Trait would be your best option.
To include a trait, you can reference it by including it at the top of your controller and then with a 'use' statement after the class declaration for the controller. Here is an example:
use App\Traits\ExampleTrait;
class CarController extends Controller
{
use ExampleTrait;
...
You would do the same in the UserController. Then, any method that you place in the ExampleTrait will be directly accessible from the CarController and the UserController by referencing it as $this->methodName(), just like referencing any other method in the same controller.
In your particular case, I would say that your logic should probably be stored in the User model, since the cars for a user are really an ATTRIBUTE of the User model, but the above gives you another option to work with.
In my humble opinion you should not call another controller in a controller.
It looks like you have some business logic in that controller. So you should move your logic to the entity (User.php) and call it in both controllers methods.
A regular controller returns a view (at least that is what is expected), so if you want to call another controller you should just send that route to that method (in web.php file) instead of calling it in another controller.
Hope that helps you.
You can call one controller function from another but the best way is to create a trait and use it both the controllers like:
trait Common
{
public function method(){}
}
class FirstController extends Controller
{
use Common;
}
class SecondController extends Controller
{
use Common;
}
If you want to bind parameters to the call, you can use:
$videos = app()->call('App\Http\Controllers\StorageController#returnViewVideo',[
'course'=>$course,
'lesson'=>$lesson,
]);
The following code worked for me well. and also it also can be used in routes.php
public function mobileImageUpload(Request $request){
$this->validate($request,[
'data'=>'required',
'filetype'=>'required',
'userid'=>'required',
]);
$namespace = 'App\Http\Controllers';
$controller = app()->make($namespace.'\ImageController');
return $controller->callAction('mobileImageUpload',[$request]);
}

In Laravel Can I create a new Model Instance without new?

For example:
You can create a new model instance of User as:
new App\Model\User()
But when I use it in blade views, looks like:
new App\Model\User()->..->...
I think it is not a good way. It's not so elegant.
So I want to add some methods to achieve that I can use like below in blade views:
User::instance()->..->...
How can I achieve this? Thanks a lot!
Thanks for helping. I know it is not a good way to call model in blade views. But in some cases, sometimes I still have chance calling model in blade views for convenient.
For example, in create blade form, usually use like this:
{!!Form::model(new App\Model\User, ['url' => '/', 'class' => 'form' ])!!}
So there is chance to use model in blade views. So I want to find a elegant way to get an instance of Model instead of using new App\Model\ModelName...
Like
User::instance()
to get a new instance of \App\Model\User.
Can scopeQuery in model works?
First of all, if you understand the concept of MVC you should know the relationship between a model, view and controller.
The controller as a middle man should do the work of passing appropriate data to your view.
This is a better way to do it in Laravel.
Your controller:
use App\Model\User;
class AccountController extends Controller{
public function __construct (User $user){
$this->user = $user;
}
public function profile(){
return view('profile, ['user'=>$this->user]);
}
}
Then in your view, profile.blade.php
Welcome {{$user->name}}

How functions in the controller are chosen?

I have seen the below functionality and I don't understand how functions in controller is choosed?
class ProfilesController extends \BaseController {
public function index() {}
public function create() {}
public function store(){}
public function show($id){}
public function edit($id){}
public function update($id){}
public function destroy($id){}
}
For local.com/profiles it would call index() function and list all the profiles. For viewing any record local.com/profiles/99 it is using show() method.
For editing any record local.com/profiles/99/edit it is using edit().
Are these methods are created automatically? Please suggest me any link or document which helps in understanding Laravel better.
The links provided to you are good to understand how to implement restful urls in Laravel but you don't know what is restful.
The method naming chosen by Laravel it's a convention used to represent what each method does. It's called CRUD.
Now which method is been called depends on the HTTP Request Method.
GET /resource index resource.index
GET /resource/create create resource.create
POST /resource store resource.store
GET /resource/{resource} show resource.show
GET /resource/{resource}/edit edit resource.edit
PUT/PATCH /resource/{resource} update resource.update
DELETE /resource/{resource} destroy resource.destroy
To avoid redundant code when we have a CRUD we use resource controller.
You have to add the below route to your routes.php and the controller you have already provide.
Route::resource('profile', 'ProfilesController');
It's the same as writing
Route::get('profile', 'ProfilesController#index'));
Route::get('profile/create', 'ProfilesController#create'));
Route::post('profile', 'ProfilesController#store'));
Route::get('profile/{id}', 'ProfilesController#show'));
Route::get('profile/{id}/edit', 'ProfilesController#edit'));
Route::put('profile/{id}', 'ProfilesController#update'));
Route::patch('profile/{id}', 'ProfilesController#update'));
Route::delete('profile/{id}', 'ProfilesController#destroy'));
If you want to generate those lines. You can use Jeffreys Way generators.
See Teach a Dog to REST to understand what I'm talking about.
You can look at github Laravel page at Router.php ->
https://github.com/laravel/framework/blob/master/src/Illuminate/Routing/Router.php
Check the resourceDefaults and addResource* functions :)
--
And of course go to Laravel documentation > http://laravel.com/docs/controllers there is the info which you need for your work..
I assume you are using Resource Controllers, http://laravel.com/docs/controllers#resource-controllers.

Method in one controller calling a method in another controller, using MVC

so i have a user controller, that has methods to update profile, etc. In the system i am developing the user would need to post articles, etc. So i am confused with the design of the system. The main logic of creating articles would be housed under the article_model. But how should i call the methods?
I can create a function in the user controller that calls on the article model to create article?
I can call a method in the user controller and create an article controller and the user controller calls the method on the article controller, which in turns call the model for the main logic.
Or just directly call on a article controller that connects to the article model.
I personally feel i need to have a user controller into this system, as logically speaking a user creates article. So which design is perfect in terms of logic and best practices.
You can load multiple models in a controller, you’re not just restricting to the model in the same domain as the controller. So if you need to interface with articles in the users controller, then just load the articles model. As deceze says, you shouldn’t call other controllers in one controller; that definitely goes against MVC conventions.
In your case, any interaction with an article should be in the articles controller though, accessible at a URL like /articles/add.
I actually use codeigniter and they do it this way. If you want to post an article from your user or profile controller you can just make an instance or load your model.
class ProfileController extends BaseController {
public function __construct()
{
$this->load->model('article_model');
}
public function index(){
$this->article_model->post();
}
}
don't call a controller from another controller
you can add link to any view called with the profile that reefers to add article
if you have to call the controller from another you may have a look at codeigniter hmvc
HMVC: an Introduction and Application
Try to use this extension HMVC for CI. It's allow to call controller methods in another controllers. Something like this:
class Dashboard extends MX_Controller{
public $autoload = array();
public function __construct()
{
parent::__construct();
}
public function index()
{
$params = 'some_params';
$data['some_data'] = Modules::run('another_controller/method', $params);
}
}
Where another_controller - simple CI controller, what expand MX_Controller.

Would bypass of the controller in CodeIgniter be considered a good practice?

Is directly call to the Model class inside the View is best practice or not? Currently I am using CodeIgniter to develop an application. In different Views of my application I'm including menus that I want to pull from the database. And the thing is currently I am passing the values to the menu through the controller. If I make a common model class and call it from the View and by pass controller. So that there will be one call to Model and it will load menu from the database at once and by pass the controller. By doing this what pros and cons will come?
With codeigniter, your views should not be concerned as to where data comes from, only that it exists. Only your Controllers should be in direct contact with your Models.
It sounds like you have a common menu that you want to load in your views and you don't want to replicate that code across all your Controllers.
To solve this problem, you need to create a common controller that your primary controllers inherit from with a method that fetches the menu.
My_Controller needs to be saved to the core folder in the application directory.
class MY_Controller extends CI_Controller
{
protected function get_menu()
{
// Load your menu here
$this->load->model('menu_model');
return $this->menu_model->get_menu();
}
}
All your primary controllers will inherit MY_Controller
class Home_Controller extends MY_Controller
{
public function index()
{
$page_data = array('menu' => $this->get_menu());
$this->load->view('home/index', $page_data);
}
}
In my opinion no its not best practice. View should contact Controller and Controllers should retrieve data from Model where Model does all the logic. Controller suppose to be the glue or middleman of View and Model.
Controller passes the returned data into View and then you do your foreach loop or whatever to display it.
View should not be doing any logic. Retrieving data from database is somewhat logic.
It is a worst practise. Then why we have controller concept for MVC. :) Mainly all logics goes into Model so thats not good to call model directly.
There will not be any problem, since you are using a common controller.
Note : You should not call model directly from view.

Categories