To pass data from a controller to a view in CodeIgniter 4, follow these steps:
- Create a new controller or open an existing one.
- Create an array of data that you want to pass to the view, for example:
$data = [
'title' => 'Welcome to CodeIgniter 4!',
'message' => 'This is a demo of passing data from controller to view.'
];
PHP
3. Load the view and pass the data to it using the view() method:
return view('welcome_message', $data);
PHP
In this example, we’re loading a view named “welcome_message” and passing the $data array to it. In the view, we can access the data using the array keys, for example:
<h1><?php echo $title; ?></h1>
<p><?php echo $message; ?></p>
PHP