Close

🔰 PHP Programming Tutorial 7 - Models in CodeIgniter 4 🔰


Introduction

The Model is responsible for managing the data of the application. It receives user input from the Controller. It can contain functions to insert, update, and retrieve your application data.

Model classes reside in the /app/Models/ directory. They can be nested within sub-directories.

The basic syntax for the model is:

<?php  namespace App\Models;  use CodeIgniter\Model; use CodeIgniter\Database\ConnectionInterface; class Model_name extends Model {  	protected $db; 	public function __construct(ConnectionInterface &$db) { 		$this->db =& $db; 	}  } ?>

Let's see the following example for a better understanding of the model:

<?php  namespace App\Models;  use CodeIgniter\Model; use CodeIgniter\Database\ConnectionInterface;  class BlogModel extends Model {  	protected $db; 	public function __construct(ConnectionInterface &$db) { 		$this->db =& $db; 	}  	public function add() { 	$data = [ 		'title'		=> 'Title', 		'description'	=> 'Description' 	]; 	return $this->db 			 	->table('blog_info') 			 	->insert($data); 	}  	public function get_blog_list() { 		return $this->db 					->table('blog_info') 					->where(["status" => "1"]) 					->get() 					->getResult(); 	}  }?> 

The file name must match the class name and the first letter of the Model class must be a capital letter.

Load / Call a Model in Controller

use App\Models\model_name;

Initialize constructor:

public function __construct() { 	$db = db_connect(); 	$this->model = new model_name($db); }

If your model is located in a sub-directory, include the relative path from your model’s directory. For example, if you have a model located at /app/Models/user/Profile.php you’ll load it using:

use App\Models\user\Profile;  public function __construct() { 	$db = db_connect(); 	$this->profileModel = new Profile($db); }

Once the model is loaded, you can access all the public methods using an object with the same name as your class:

$this->profileModel>method();

Here is an example of a controller, that loads a model, then serves a view:

<?php  namespace App\Controllers; use App\Controllers\BaseController;  use App\Models\BlogModel;  class Blog extends BaseController {          public function __construct() {	 		$db = db_connect(); 		$this->blogModel = new BlogModel($db);     }  	public function index()  { 		$data[‘list’] = $this->blogModel>get_blog_list(); 		echo view('about_us', $data); 	} }  ?>

Method methods

CodeIgniter 3 CodeIgniter 4
insert();
insert();
delete();
delete();
update();
update();
row();
getRow();
result();
getResult();


😉Subscribe and like for more videos:
https://www.youtube.com/@chiragstutorial
💛Don't forget to, 💘Follow, 💝Like, 💖Share 💙&, Comment

0 Comments
Leave a message

 

Search Current Affairs by date
Other Category List

Cookies Consent

We use cookies to enhance your browsing experience and analyze our traffic. By clicking "Accept All", you consent to our use of cookies. Cookies Policy