So, I'm getting a fatal error because the method is undefined when the controller calls the method. Though this is not true as the method is inside the classes model.
StudentsController.php
<?php
class StudentsController extends AppController{
public function index(){
$students = $this->Student->find('all');
$this->set('students', $students);
}
public function add(){
if($this->request->is('post')){
$this->formatData($this->request->data);
}
}
}
?>
And then my model:
Student.php (Model)
<?php
class Student extends AppModel{
var $studentData;
public function formatData($studentData){
if(is_null($studentData)){
return false;
}else{
echo $studentData;
}
}
}
?>
You're not invoking the method on the model, but on the controller where there is no such method available, hence the error.
While the controller may automatically load the model, it doesn't expose its API, it just makes an instance of the model available via magic property accessors.
So instead of
$this->formatData($this->request->data);
you have to invoke the method on the model like this:
$this->Student->formatData($this->request->data);
See also
http://book.cakephp.org/2.0/en/controllers.html#Controller::$uses
http://book.cakephp.org/2.0/en/controllers.html#Controller::loadModel
http://book.cakephp.org/2.0/en/models.html#understanding-models
Related
I have been facing a problem of not able to use the model inside the controller in the new laravel framework version 5. i created the model using the artisan command
"php artisan make:model Authentication" and it created the model successfully inside the app folder, after that i have created a small function test in it, and my model code looks like this.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
echo "This is a test function";
}
}
Now i have no idea, that how shall i call the function test() of model to my controller , Any help would be appreciated, Thanks in advance.
A quick and dirty way to run that function and see the output would be to edit app\Http\routes.php and add:
use App\Authentication;
Route::get('authentication/test', function(){
$auth = new Authentication();
return $auth->test();
});
Then visit your site and go to this path: /authentication/test
The first argument to Route::get() sets the path and the second argument says what to do when that path is called.
If you wanted to take this further, I would recommend creating a controller and replacing that anonymous function with a reference to a method on the controller. In this case, you would change app\Http\Routes.php by instead adding:
Route::get('authentication/test', 'AuthenticationController#test');
And then use artisan to make a controller called AuthenticationController or create app\Http\Controllers\AuthenticationController.php and edit it like so:
<?php namespace App\Http\Controllers;
use App\Authentication;
class AuthenticationController extends Controller {
public function test()
{
$auth = new Authentication();
return $auth->test();
}
}
Again, you can see the results by going to /authentication/test on your Laravel site.
Use scope before method name
<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
class Mainmenu extends Model
{
public function scopeLeftmenu() {
return DB::table('mainmenus')->where(['menu_type'=>'leftmenu', menu_publish'=>1])->orderBy('menu_sort', 'ASC')->get();
}
}
above code i tried to access certain purpose to call databse of left menu
than we can easy call it in Controller
<?php
Mainmenu::Leftmenu();
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function scopeTest(){
echo "This is a test function";
}
}
Just prefix test() with scope. This will become scopeTest().
Now you can call it from anywhere like Authentication::Test().
For me the fix was to set the function as static:
public static function test() {..}
And then call it in the controller directly:
Authentication::test()
You can call your model function in controller like
$value = Authentication::test();
var_dump($value);
simply you can make it static
public static function test(){
....
}
then you can call it like that
Authentication::test();
1) First, make sure your Model is inside a Models Folder
2) Then supposing you have a model called Property inside which you have a method called returnCountries.
public function returnCountries(){
$countries = Property::returnCountries();
}
of course, in your case, replace Property by the name of your Model, and returnCountries by the name if your function, which is Test
and in the Model you write that function requesting the countries
so in your Model, place a:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
return $test = "This is a test function";
}
}
and this is what your Controller will be getting
You should create an object of the model in your controller function then you can model functions inside your controller as:
In Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
return "This is a test function"; // you should return response of model function not echo on function calling.
}
}
In Controller:
namespace App\Http\Controllers;
class TestController extends Controller
{
// this variable is used to store authenticationModel object
protected $authenticationModel;
public function __construct(Request $request)
{
parent::__construct($request);
$this->authenticationModel= new \App\Authentication();
}
public function demo(){
echo $this->authenticationModel->test();
}
}
Output:
This is a test function
I am creating a website using laravel. I have a small issue with eager loading. I have already made several websites with laravel, but still I can't find what is wrong here.
This is my config model:
<?php
class Config extends \Eloquent {
protected $table = "configs";
public function groups() {
return $this->hasMany('ConfigOptionGroup', 'config_id');
}
}
And this is my testcontroller class:
<?php
namespace WebsiteController;
class DemoController extends \BaseController {
public function getTest() {
$c = \Config::where('id', 1)->with(['groups' => function($q){
$q->whereNull('config_option_group_id');
}])->first();
return $c;
}
}
Whenever I surf to the url that calls the getTest method I get an error saying Call to undefined method Illuminate\Database\Query\Builder::groups(). However, the function groups() exists in the Config model.
When I remove the with() function from the query, it works just fine. But I can never load the groups via the relation.
Is there anyone who can help me with this problem?
Update: I have removed the Config facade by commenting out the line in /app/config/app.php.
I'm developing an API to acces some data on my database. I'm creating a controller for each part of the API. For example, I will have a controller to attend API calls to get a film list (FilmsController) and other controller to attend API calls to get a director list (DirectorsController)
Each controller will have a basic set of methods (getList, getInfo) so I made an ApiController to use as the base for the others. In the ApiController I have the basic set of methods but I have to call the models in non very polite way.
I'm I missing something? Is there any other way to call the models dynamically? I'm using the controllers wrong?
Here is the code, thanks.
class ApiController extends BaseController {
protected $model = '';
public function getList()
{
$items = call_user_func(array($this->model,'all'));
return Response::json($items);
}
...
}
And the FilmsController
class FilmsController extends ApiController {
protected $model = 'Film';
}
Am I going with a bad design?
If you really want to bind model to controller, it would be better to use Laravel IoC container and its automatic resolution feature.
class ApiController extends BaseController {
protected $model;
public function getList()
{
$items = $this->model->all();
return Response::json($items);
}
}
class FilmsController extends ApiController {
public function __construct(Model $model)
{
$this->model = $model;
}
}
Find more about this in documentation
why you call model using variable and use call_user_func function
you can just create ApiController as abstract class and you override the basic set of methods (getList, getInfo) into FilmsController and DirectorsController then you can use Film Model
ApiController:
class ApiController extends BaseController {
public function getList()
{
}
FilmsController:
class FilmsController extends ApiController {
public function getList()
{
$items = Film::all();
return Response::json($items);
}
}
how to call model method in another model, example
I have code like this
/model/user.php
public function get_token_by_id($id){
//some code
}
i want call in my another model
/model/restaurant
App::bind('user','user');
class RestaurantController extends BaseController {
public function __construct(user $modelUser){
$this->modelUser = $modelUser;
}
public function getUser(){
$someVar = $this->modelUser->get_token_by_id($id);
}
}
But i get an error
Call to a member function get_token_by_id() on a non-object
how to fix it?
Well... that's because $this->modelUser is a non object !
To be more precise, $this->modelUser returns null or something like that (try a var_dump($this->modelUser)). It could be because your model doesn't have the attribute declaration (protected $modelUser) or because you don't pass the right variable into the constructor.
I get the error
Fatal error: Call to a member function retrieve_products() on a non-object
The controller is:
<?php
class Cart extends CI_Controller { // Our Cart class extends the Controller class
public function _construct()
{
parent::_construct(); // We define the the Controller class is the parent.
$this->load->model('Cart_model'); // Load our cart model for our entire class
}
function index()
{
$data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products
}
}
The model is:
<?php
class Cart_model extends CI_Model {
function retrieve_products(){
$query = $this->db->get('products'); // Select the table products
return $query->result_array(); // Return the results in a array.
}
}
I want to say that your call
$data['products'] = $this->cart_model->retrieve_products();
Should be:
$data['products'] = $this->Cart_model->retrieve_products();
Ie: uppercase "C" in cart_model
Maybe we're using different versions (I have 1.7.2), but to declare a model, CI_ does not appear. My working code has the equivalent of:
class Cart_model extends Model
Also, the class should capitalized:
$this->Cart_model->retrieve_products();
(instead of)
$this->cart_model->retrieve_products();
I think its your typo error you have spelled construct function as _construct rather than __construct thats why codeigniter considers it as a function rather than a class constructor and model loading is limited to only that function.