Codeigniter 4 – Getting records from a Model and sending them to a View with Example

Getting Records from Model

- Use the get() method to retrieve records from the database.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';

    public function getUsers()
    {
        return $this->get();
    }
}

Getting Specific Records

- Use the where() method to filter records based on conditions.

Example:

public function getUsers($name)
{
    return $this->where('name', $name)->get();
}

Getting Records with Relationships

- Use the with() method to retrieve related records.

Example:

public function getUsers()
{
    return $this->with('posts')->get();
}

Sending Records to View

- Use the view() method to send records to a View.

Example:

namespace App\Controllers;

use App\Models\User;

class UserController extends BaseController
{
    public function index()
    {
        $userModel = new User();
        $users = $userModel->getUsers();
        return view('users/index', ['users' => $users]);
    }
}

Passing Records to View as Array

- Use the toArray() method to convert records to an array.

Example:

return view('users/index', ['users' => $users->toArray()]);

Passing Records to View as JSON

- Use the toJson() method to convert records to JSON.

Example:

return view('users/index', ['users' => $users->toJson()]);

I hope this helps! Let me know if you have any further questions or need more information.

Note: Getting records from a Model and sending them to a View in CodeIgniter 4 provides a simple and intuitive way to display data in your application. It helps to keep the code organized and maintainable.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0