CodeIgniter - Call to a member function model() on a non-object [duplicate] - codeigniter

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 9 years ago.
I have a login form that is being created in the view. Then in my controller I'm trying to load my model but it doesn't seem to load. Looked up a few answer here on stackoverflow and almost everybody says autoload model, import the database library,etc. I did that but I'm still getting the error
Fatal error: Call to a member function model() on a non-object in C:\xampp\htdocs\\project\application\controllers\login.php on line 11
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Login::$load
Filename: controllers/login.php
Line Number: 11
login_view
<?php
$loginEmail = array('placeholder' => "Email", 'name' => "loginEmail");
$loginPassword = array('placeholder' => "Wachtwoord", 'name' => "loginPassword");
$loginSubmit = array('name' => "loginSubmit", 'class' => "btn", 'value' => "Inloggen");
$loginForgot = array('name' => "loginForgot", 'class' => "link", 'value' => "Wachtwoord vergeten?");
echo form_open('login/login', array('class' => 'grid-100 formc'));
echo form_input($loginEmail);
echo form_password($loginPassword);
echo form_submit($loginSubmit);
echo form_submit($loginForgot);
?>
login_controller
<?php
Class Login extends CI_Controller{
function index(){
$data['content'] = 'login_view';
$this->load->view('templates/template', $data);
}
function login(){
$this->load->model('login_model');
$query = $this->login_model->validate();
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'loggedin' => true
);
$this->session->set_userdata($data);
redirect('profile/myprofile');
}
}
}
?>
login_model
<?php
Class Login_model extends CI_Model{
function validate(){
$this->db->where('email', $this->input->post('loginEmail'));
$this->db->where('password', md5($this->input->post('loginPassword')));
$query = $this->db->get('tbl_users');
if($query->num_rows == 1){
return true;
}
}
}
?>
autoload.php
$autoload['libraries'] = array('database', 'session');
What am I missing here?

You don't have a constructor, in your login controller:
public function __construct() {
parent::__construct();
}

According to CodeIgniter docs
If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it:
parent::__construct();
Refer CI Constructor for more.

Related

Laravel putting the return of a trait array into the controller

I'm currently struggling with how to return a variables from a trait and it should be returned in the array to be used in the controller:
Trait:
public function getAllData($search)
{
if ($search->search == null) {
$search->search = '#technology';
}
$cb = new Codebird();
$cb->setConsumerKey(env('TwitterKey'), env('TwitterSecret'));
$cb->setToken(env('AccessToken'), env('AccessTokenSecret'));
//https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
//https://dev.twitter.com/docs/api/1.1/get/search/tweets
$params = [
'q' => $search->search,
'lang' => 'en',
'count' => '5',
];
$reply = (array)$cb->search_tweets($params);
$data = (array)$reply['statuses'];
$s = count($reply['statuses']);
return [
'data' => $data,
's' => $s,
];
Controller:
public function TwitterData(Request $search) {
$data = $this->getAllData($search);
return view('front.search', compact('data'));
}
It currently gives me an error saying about using the object however I can't access the 'data' in the array
Error:
Trying to get property of non-object (View: C:\xampp\htdocs\TwitterProject\resources\views\front\search.blade.php)
You are returning an array on your getAllData method, but you are probably trying to access it as an object on your View:
WRONG:
{!! $data->data !!}
RIGHT:
{!! $data['data'] !!}

Codeigniter - Hook to log GET / POST REQUESTS

A client requires that all GET/POST requests are logged and stored for 90 days for their applicaiton. I have written a HOOK which seems to record some of the GETS / POSTS but there is less data than I would expect. For example, when submitting form data, the entries don't seem to be put in the log. Has anyone written something similar which works?
Here is my version thus far:
class Logging {
function __construct() {
$this->CI =& get_instance();
}
function index() {
$this->CI->load->model('Logging_m');
$this->CI->load->model('Portal_m');
//get POST and GET values for LOGGING
$post = trim(print_r($this->CI->input->post(), TRUE));
$get = trim(print_r($this->CI->input->get(), TRUE));
$this->CI->Logging_m->logPageView(array(
'portal_id' => $this->CI->Portal_m->getPortalId(),
'user_id' => (!$this->CI->User_m->getUserId() ? NULL : $this->CI->User_m->getUserId()),
'domain' => $_SERVER["SERVER_NAME"],
'page' => $_SERVER["REQUEST_URI"],
'post' => $post,
'get' => $get,
'ip' => $this->CI->input->ip_address(),
'datetime' => date('Y-m-d H:i:s')
));
}
}
This data is stored in a model called 'Logging_m' which looks like this:
<?php
class Logging_m extends CI_Model {
function __construct() {
parent::__construct();
}
function logPageView($data) {
$this->db->insert('port_logging', $data);
}
}
/* End of file logging_m.php */
/* Location: ./application/models/logging_m.php */
As mentionned by Patrick Savalle you should use hooks. Use the post_controller_constructor hook so you can use all other CI stuff.
1) In ./application/config/config.php set $config['enable_hooks'] = TRUE
2) In ./application/config/hooks.php add the following hook
$hook['post_controller_constructor'] = array(
'class' => 'Http_request_logger',
'function' => 'log_all',
'filename' => 'http_request_logger.php',
'filepath' => 'hooks',
'params' => array()
);
3) Create the file ./application/hooks/http_request_logger.php and add the following code as example.
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Http_request_logger {
public function log_all() {
$CI = & get_instance();
log_message('info', 'GET --> ' . var_export($CI->input->get(null), true));
log_message('info', 'POST --> ' . var_export($CI->input->post(null), true));
log_message('info', '$_SERVER -->' . var_export($_SERVER, true));
}
}
I've tested it and it works for me (make sure you have logging activated in your config file).

codeigniter access model from library

I am trying to integrate the following code into my project. it is held in a library
function do_std_login($email, $password) {
$CI =& get_instance();
$login = $CI->users_model->login($email, md5($password));
if($login){
$session_array = array(
'user_id' => $login->user_id,
'name' => $login->name,
'type' => 'Standard'
);
$CI->session->set_userdata($session_array);
// Update last login time
$CI->users_model->update_user(array('last_login' => date('Y-m-d H:i:s', time())), $login->user_id);
return true;
} else {
$this->errors[] = 'Wrong email address/password combination';
return false;
}
}
I am calling it this way:
$login = $this->jaclogin->do_std_login($this->input->post('email'),$this->input->post('password'));
but when I run it I get the following error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Login::$users_model
Filename: libraries/jaclogin.php
Line Number: 45
I have check I am do load the correct library in the codeigniter autoload file.
Any Ideas?
Thanks
Jamie Norman
Using your CI instance, load your model explicitly in the library like so..
function do_std_login($email, $password) {
$CI =& get_instance();
//--------------
$CI->load->model('users_model'); //<-------Load the Model first
//--------------
$login = $CI->users_model->login($email, md5($password));
if($login){
$session_array = array(
'user_id' => $login->user_id,
'name' => $login->name,
'type' => 'Standard'
);
$CI->session->set_userdata($session_array);
// Update last login time
$CI->users_model->update_user(array('last_login' => date('Y-m-d H:i:s', time())), $login->user_id);
return true;
} else {
$this->errors[] = 'Wrong email address/password combination';
return false;
}
}

Validation in my CakePHP seems disabled

I'm following the blog tutorial on CakePHP website, but validation doesn't work and I don't understand why, because I'm using the blog tutorial code.
I'll report directly from my files anyway...
MODEL
class Post extends AppModel
{
var $name = 'Post';
var $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
CONTROLLER
class PostsController extends AppController {
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
function view($id) {
$this->Post->id = $id;
$this->set('post', $this->Post->read());
}
function add() {
if (!empty($this->data)) {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
}
VIEW (add view)
<h1>Add Post</h1>
<?php
echo $form->create('Post');
echo $form->input('title');
echo $form->input('body', array('rows' => '3'));
echo $form->end('Save Post');
?>
When I reach the /posts/add page and then click to Save without any input text it doesn't reload with error; it inserts the empty data into db and then redirects me with the message "Your post has been saved".
Why doesn't validate itself? I've read into docs that it's not necessary to call validate(); save() is enough.
Any ideas about this?
I found the error: I was naming the model files capitalizing them. So, I had a Post.php instead of a post.php.
CakePHP didn't find my models and so it was using its "generated" models.

Why aren't validation errors being displayed in CakePHP?

I'm trying to perform validation in the login page for the name,email and password fields. If the input fails validation,the error message should be displayed.
But here,when I fill in the details and submit, it is redirected to the next page. Only the value is not saved in the database.
Why is the message not displayed?
This is my model:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
'email_id' => 'email'
);
function loginUser($data) {
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
$login = $this->find('all');
foreach ($login as $form):
if ($this->data['User']['email_id'] == $form['User']['email_id'] && $this->data['User']['password'] == $form['User']['password']) {
$this->data['User']['id'] = $this->find('all',
array(
'fields' => array('User.id'),
'conditions' => array(
'User.email_id' => $this->data['User']['email_id'],
'User.password'=>$this->data['User']['password']
)
)
);
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
function registerUser($data) {
if (!empty($data)) {
$this->data['User']['name'] = $data['User']['name'];
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
if($this->save($this->data)) {
$this->data['User']['id']= $this->find('all', array(
'fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
}
This is my controller:
class UsersController extends AppController {
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function login() {
$userId = $this->User->loginUser($this->data);
if($userId>0) {
$this->Session->setFlash('Login Successful.');
$this->redirect('/forms/homepage/'.$userId);
break;
} else {
$this->flash('Login Unsuccessful.','/forms');
}
}
function register() {
$userId=$this->User->registerUser($this->data);
$this->Session->setFlash('You have been registered.');
$this->redirect('/forms/homepage/'.$userId);
}
}
EDIT
Why is the message,example,"Minimum 8 characters long", is not being displayed when give less than 8 characters in the password field?
<!--My view file File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="appTitle">
<h2> formBuildr </h2>
</div>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->error('User.name','Name not found');
echo $form->input('User.email_id');
echo $form->error('User.email_id','Email does not match');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Your validation seems correct
How about trying the following:
Make sure set your $form->create to the appropriate function
Make sure there is no $this->Model->read() before issuing Model->save();
Edit
Did you have the following?:
function register()
{
//do not put any $this->User->read or find() here or before saving pls.
if ($this->User->save($this->data))
{
//...
}
}
Edit2
IF you're doing a read() or find() before saving the Model then that will reset the fields. You should be passing the variable as type=hidden in the form. I hope i am making sense.
Edit3
I think you need to move your registerUser() into your controller because having that function in the model doesn't provide you a false return. it's always going to be true even if it has validation errors.
Comment out the redirect line and set the debug to 2 in config/core.php. Then look at the sql that is being generated to see if your insert is working. If the errors are not being displayed, maybe in the view, you are using $form->text or $form->select instead of the $form->input functions. Only the $form->input functions will automatically display the error messages.

Resources