Categories
Laravel Programming

Laravel 5.8 Creating a MVC project with CRUD in 5 steps

This Laravel tutorial deals with the Installation, Setup and Basic Laravel MVC usage to open a page with intro to the CRUD operations.

Don’t know how to setup a new Laravel project or you are a 20 year old pro who is too pro to touch the basics? This is the right place to be.  I’ll keep referencing this tutorial whenever Installation is needed in my other Laravel posts.

It is expected that you are familiar with the basics of windows and linux server administration. If you need more help then please use Google. But I will try to avoid the basics to make sure that the goals are achieved without any fuss.

Now I don’t joke around. As per the tradition of this blog, I will make sure that you achieve this goal with the least effort wasted on figuring out wtf is this blog talking about. Let me know in the comments if you find it helpful. So let’s get started!

The 12345 Steps 🙂 :

  1. Setup of new project and running the server to make sure it bites.
  2. Creating a Database (mysql)
  3. Performing Migration to create schema
  4. Controller to repeatedly insert and render a View
  5. Test! and Conclusion

1. Setup and running new project

Lets learn how to install a new Laravel project with running a server on default port 8000.

Before we start, it is important that you should simply follow the official documentation for the latest Laravel Version installation guideline. I don’t want you to look backward when mentioning my blog. 

Source: https://laravel.com/docs/5.8/installation

So create a folder in your drive and open the console in it like so:

Opening the Laravel root project folder in windows command prompt or terminal
Opening the Laravel root project folder in windows command prompt or terminal

Now, lets create a project by running the following command in console:

laravel new codeonion_tutorial 

This creates a “codeonion_tutorial” folder and will start downloading the assets we need.

Creating a new Laravel project
Creating a new Laravel project

After a decade of waiting, the project will be ready. Now let’s make sure that it is running.

  • I go into the codeonion_tutorial project by  cd codeonion_tutorial
  • Start the Server:

php artisan serve

  • Visit the IP address as provided by the console output. Mine by default shows http://localhost:8000
  • So it works. You can now create a database.

2. Creating a Database (mysql)

Lets learn how to create a database in phpmyadmin for a Laravel project. But first, lets enjoy this breathtaking performance by the star of this blog.

Dancing Banana
Dancing Banana

You might be using XAMPP, LAMPP or plain old terminal based mysql server. I don’t care. AS a professional, you must have to know how to create a database. Heck! You must be able to follow this tutorial with using other database engines as well. So help yourself and learn that part as well. Let me know if you want me to make a tutorial about that. Otherwise, just keep following.

I am using Windows and Xampp. Run the Mysql server and open phpmyadmin

Running a Xampp Server for phpmyadmin
Running a Xampp Server for phpmyadmin

Then visit http://localhost/phpmyadmin/

phpmyadmin interface
phpmyadmin interface

Now, let’s create a database. Press New as shown below:

Create a new Database in phpmyadmin
Create a new Database in phpmyadmin

A Create database page will open which is explained below:

Write name of database and press create
Write name of database and press create
  1. Write name of your database to be.
  2. Press Create
  3. Done! (but also note these sub points)
    1. It could
      1. Fail if it violates any rules of database server
      2. It could also fail if your database is not allowed
      3. It could also fail if your Hosting service limits you by number of databases you can make
    2. Now how many bloggers would tell you about these things !! ;D

3. Performing Migration to create schema

Here, lets learn how to perform migrations and database configuration in Laravel.

Nothing is easy nowadays. You have publishers destroying true game developers and companies and then you have web frameworks made confusing by ignorant bloggers. I am all of them combined. So let’s configure our project database for migrations.

  • Our composer installation of the Laravel has already set the .env configuration file in place. But let’s do that manually to exercise the process.
Pointing out the .env configuration file of the Laravel Project
Pointing out the .env configuration file of the Laravel Project
  • Go to the terminal/command line and execute the following command

The .env file will be created and we will now configure it for our database. Open the .env file in the root folder of your newly created project and find the following highlighted database configuration

Editing the .env configuration file in Laravel
Editing the .env configuration file in Laravel

Lets set it to match our database

Laravel default phpmyadmin mysql configuration
Laravel default phpmyadmin mysql configuration

Migrations

First we have to clean the migration files created by composer. Go to the database/migrations/ folder and delete all files.

Now let’s create a migration file. Execute the following command from the root folder of the project.

php artisan make:migration create_messages_table
Creating migration files in Laravel
Creating migration files in Laravel

Now from the root folder, go to database/migrations/ folder and open the latest file which was created. Migration file that was created for me was:

2019_07_14_162743_create_messages_table.php

It has a timestamp along with the name I designated in the filename.

Open the file and lets add commands to create our “messages” table..

Initially, it will contain up and down functions (which handle what happens when we want the executions to be at up or down state in our database server).

Basic Laravel migration file usage
Basic Laravel migration file usage

Lets add the following line after the “id” column line in the up() function

$table->string(‘message’);

Editing the laravel migration file to refer to the table column
Editing the laravel migration file to refer to the table column

Lets run the migration using 

php artisan migrate

Laravel migration process
Laravel migration process

Note that if you screwed up, then you can “undo” the migration using php artisan migrate:rollback but it is not necessary to do now.

At this time, go to phpmyadmin and you will see that our table has been created.

Table updated in phpmyadmin after migration was performed in Laravel
Table updated in phpmyadmin after migration was performed in Laravel

Now, lets make a web page which repeatedly inserts into that table and fetches all and displays into a page. Sweet!

4. Controller to repeatedly insert and render a View

Lets learn how to create a Model, controller, view and route for our Laravel project.

Our database is connected, migrations are up. Now we need to populate the table and then we need to display it on the screen. So lets start without any regular fuss that I am used to deliberately provide to you include this once.

MODEL CREATION

Lets learn how to create a Model for the messages table. This model will be used by the controller.

First, lets create a model by executing this command

php artisan make:model Message

Open the model file at root/app/Message.php and change its content to make sure that it points to the correct table. Add the highlighted line and save it.

Model referring to the database table
Model referring to the database table

Now we can use the model in our controller.

CONTROLLER CREATION

Lets learn how to make a controller for our view. This controller will call out modal to add a random message and fetch all messages.

We need to create a controller. From the root folder, execute this command
php artisan make:controller MessageHandler

Creating a controller in Laravel using command line
Creating a controller in Laravel using command line

This will create a controller file in rootfolder/app/Http/Controllers

Open the root/app/Http/Controllers/MessageHandler.php and change the contents of the controller file as follows:

Laravel controller to insert into table  and get all the records to display in a web page
Laravel controller to insert into table and get all the records to display in a web page

This controller code:

  1. Creates a random message
  2. Saves it to the database in messages table.
  3. Retrieves all the messages
  4. Displays them in separate lines

Now, let’s make a route

ROUTE

Lets learn how to make a route for our controller.’s process_and_display action

Open root/routes/web.php and add this to the bottom of it:

Route::get(‘show_message’, ‘MessageHandler@process_and_display’);

We are now done with the MVC!

5. Test! and Conclusion

So we have done it all. Lets go to the http://localhost:8000/show_message and see what happens after we refresh the page several times.

Successfully showing the tutorial output
Successfully showing the tutorial output
[jetpack_subscription_form show_only_email_and_button=”true” custom_background_button_color=”undefined” custom_text_button_color=”undefined” submit_button_text=”Dancing BananaSubscribe For More” submit_button_classes=”undefined” show_subscribers_total=”true” ]

You should now review the above steps. Go over the project you created and learn what was done in each step.Read documentation and learn more.

Please let me know in the comments about this post and tell me if there is more I can do. We have now learnt about Installation, Setup and Basic Laravel MVC usage to open a page with intro to the CRUD operations .

android autocomplete camera code codeiginter 3 Codeigniter codeigniter 3 computer vision CSS database education files help helpful how how to HTML HybridIgniter installation java knoppix laravel learn libraries linux mobile mvc open opencv OpenCV4Android PHP plugin project responsive review Review – Web Design WYSIWYG SDK solution touchpad tutorial upload Video web design wordpress WYSIWYG

Categories
Codeigniter Programming

CodeIgniter 3 – Create your own Hello World with simple form and database!

In the previous tutorial, you you learnt how to remove the “index.php” from URL. Now, we are ready for the “Hello World!” complete with code

GOALS!

In this tutorial, we will learn CodeIgniter 3 MVC by making a Hello World! program, complete with database, introduction to CRUD operations, form, switching pages and code. We will cover a LOT in this tutorial and I am sure you will get a lot of knowledge about CodeIgniter 3. Check the following list to see what you will learn.

  1. Create a database to be used by Model
  2. Connect the database to the web application
  3. Create a custom model:
    • Model will use the Database
    • model will contain a “Hello World!” in a function as a return value for controller to use.
  4. Create two custom views:
    • We will Load views from controller.
    • Pass data to the views using controller.
    • Use data from controller in Views.
    • Make a form which will work along with Controller.
    • Call controller custom function.
    • Pages association (move from page to page)
  5. Create a controller that will:
    • Load the model.
    • Use model function in controller.
    • Receive input from model in controller.
    • Interact with database using model.
    • Pass data to views using data[] array.
    • Create custom controller function.
    • Load views.
    • Load view from a button in another view.
    • Use helper;
    • Use constructor.

As you can see, this is a seriously deep “Hello World!” tutorial. I am sure that you will learn a lot in the end. You will be prepared to learn more without having to worry about learning the basics. Lets get started!

BEGIN!


Creating the Database

1. Create a Database

We will create a database to be used for this tutorial.

  1. In XAMPP, go to localhost/phpmyadmin/
  2. Create a  database called “citutorial
  3. Create a table using this SQL query
    CREATE TABLE `citutorial`.`helloworldtable` ( `id` INT NOT NULL AUTO_INCREMENT , `message` VARCHAR(255) NOT NULL , PRIMARY KEY (`id`) ) ENGINE = InnoDB;
  4. Now make a simple “Hello World!” entry in the table so that the table has just a single entry of
    id = 1
    message = Hello World!

Eventually, your table should look like this,

 

2. Connect the Database

Go to the /application/config/database.php and modify the settings for the database citutorial. You need to input the database username, password and database name. By default, the username in XAMPP is “root” and password is empty i.e. “”. And the database name is “citutorial. So the settings are,

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'citutorial',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Creating the Model

Understanding the Model

We will now understand the model which will retrieve the “Hello World!” message from the database table we created in steps 1 & 2. First, I will show you what method I used and then you will get the entire model code.

For this tutorial, I have first selected the “table” in our database using this line of code.

// $this->db->from("NAME_OF_TABLE");
$query = $this->db->from("helloworldtable");

Then, I provided the criteria to find the “Hello World!” message from the table like this. Note that in the following line of code, “message” is the column name and “Hello World!” is the specific search keyword that is to be matched in order to retrieve the value.

//$this->db->where('TABLE_COLUMN_NAME', "SEARCH_KEYWORD");
$query = $this->db->where('message', "Hello World!");

Then, I checked if the query was successful and performed an action on the basis of the success or failure of the query like so.

if(!$query){
	echo "Failed to find the \"Hello World\" Entry<br>";
}else{
	echo "Successfully found the \"Hello World\" Entry<br>";
	return $this->db->get()->result();
}

Note that in the end, I simply returned the result of the query like this.

return $this->db->get()->result();

(Alternative approach)

Now, note that all of this could also have been done using the following model function (which I won’t use).

function return_helloworld_message(){
	$this->db->from("helloworldtable");
	$this->db->where('message', "Hello World!");
	return $this->db->get()->result();
}

3. Creating the model

Lets finally create the model file and add the code.

  1. Go to \application\models\1_hello_world\ and create a file called “Helloworld_model.php”.
  2. Double check that the file name starts with a capital letter since it is important in CI3.0+ versions.
  3. Now, open the file and add the following code to it.
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Helloworld_model extends CI_Model {
    
    	public function __construct()
        {
                // Call the CI_Model constructor
                parent::__construct();
        }
    
        function return_helloworld_message(){
        	// From the given table,
        	$query = $this->db->from("helloworldtable");
    
        	// Find where the column "message" has a value called "Hello World!"
        	$query = $this->db->where('message', "Hello World!");
    
        	// Check if the query was successful
        	if(!$query){
        		echo "Failed to find the \"Hello World\" Entry
    ";
        	}else{
        		echo "Successfully found the \"Hello World\" Entry
    ";
        		return $this->db->get()->result();
        	}
        	// Then, return the value from Model to the calling controller
        }
    }
    

This completes the model to be used in this tutorial.  Next, we will prepare our views to receive the input.


 

Creating the Views

For this tutorial, we will make two views.

  1. First view will be used to request a “Hello World!” query.
  2. Second view will be used to show the output (either failure or success)

4.1 Creating a view to request for a “Hello World!” message

This view will show a page which will ask the user to press a button to perform a request. Here are some points to note:

Follow these steps to make the request view..

  1. Go to \application\views\1_hello_world\ and create a file called “request_a_helloworld_message.php”.
  2. Add the following code to it.
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    ?>
    <?php 
    
         echo $buttonText;
         echo $pageTitle;
         echo $heading;
    ?>
    <form action="<?php echo base_url();?>1_hello_world/helloworld/requestModel" method="post">
    <?php echo $button_info; ?>
    <input type="submit" value="<?php echo $buttonText; ?>" />
    </form>

4.2 Creating a view to show result

Upon completion of the request, an output message will be generated. This could contain either the “Hello World!” or an error message informing us about the failure to find the “Hello World!” message in database table.

    1. Go to \application\views\1_hello_world\ and create a file called “resultDisplay.php”.
    2. Add the following code to it
      <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
      <?php
            echo pageTitle;
            foreach ($modelData as $row) { 
                  echo $row--->message;
            }
      ?>
      <form action="&lt;?php echo base_url();?&gt;1_hello_world/helloworld/" method="post">
      	<input type="submit" value="<?php echo $buttonText; ?>" />
      	
      	<table>
      		<tr>
      			<td><?php echo $button_info; ?></td>
      		</tr>
      	</table>
      </form>

 

Creating the Controller

Now comes the really interesting component of CodeIgniter. The Controller! The controller will allow us to perform the following functions of the Hello World! tutorial application.

    1. Load the database to be used by the Model.
    2. Allow switching between two views with a button.
    3. Send data from controller and model to the view.
    4. Loading views.
    5. Calling model functions and passing its result into the view.

Now, lets first understand how I used the controller in this tutorial.

Understanding the Controller

In my controller. I have two functions which are,

    1. index() function which by default loads a request view.
    2. requestModel() function which is called by clicking a button in the “request_a_helloworld_message.php”  view.

 

index()

In this function, I am simply loading a view and passing data to it. The data is passed as an array like this,

$data['pageTitle'] = "Codeonion Tutorials!";
$data['heading'] = "Welcome to Hello World! Request page!";
$data['button_info'] = "Press the button to see the message from model.";
$data['buttonText'] = "Submit a Request to model";

The reason I have done it is to show you how it is possible to control the data you wish to show in view from the controller, instead of actually typing it into the view as simple HTML.

When loading views, it is possible to pass data to it. You can even load entire views into variables and pass them into the view.

$this->load->view('1_hello_world/request_a_helloworld_message', $data);

 

requestModel()

In this function, I am calling a model function and basically passing its result into the view.

I am calling a model and giving it a name of “helloworldmodel” like this,

$this->load->model('1_hello_world/Helloworld_model', 'helloworldmodel');

Afterwards, I have called a model function called “return_helloworld_message()” and stored its output in “$data[‘modelData’]” like this,

$data['modelData'] = $this->helloworldmodel->return_helloworld_message();

Finally, as before, I have loaded a view to show results and passed data to it like this.

$this->load->view('1_hello_world/resultDisplay', $data);

 

5. Creating the controller

Now, we will finally create a controller and put the code in it.

  1. Go to \application\controllers\1_hello_world\ and create a Helloworld.php” and make sure that the file name starts with a capital letter
  2. Copy the following code into the Helloworld.php controller.
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Helloworld extends CI_Controller {
    	public function __construct()
            {
                parent::__construct();
                // Helpers and libraries called in constructor will be available
                // in every function of this Helloworld controller class
                $this->load->database();
                $this->load->helper("URL");
            }
    
    	public function index(){
    
    		// General strings stored in $data array
    		// These are to be displayed in the "request_a_helloworld_message" view
    		$data['pageTitle'] = "Codeonion Tutorials!";
    		$data['heading'] = "Welcome to Hello World! Request page!";
    		$data['button_info'] = "Press the button to see the message from model.";
    		$data['buttonText'] = "Submit a Request to model";
    
    		// And we pass the data into the view.
    		$this->load->view('1_hello_world/request_a_helloworld_message', $data);
    	}
    
    	public function requestModel(){
    
    		// General Variables just like in index() function of this controller
    		$data['pageTitle'] = "Codeonion Tutorials!";
    		$data['heading'] = "This is the result!";
    		$data['button_info'] = "Press the button to see the Hello World! message.";
    		$data['buttonText'] = "Back";
    
    		// We load the model
    		$this->load->model('1_hello_world/Helloworld_model', 'helloworldmodel');
    
    		// We store the result of modal function in $data array
    		$data['modelData'] = $this->helloworldmodel->return_helloworld_message();
    
    		// We pass $data array into the "resultDisplay" view
    		$this->load->view('1_hello_world/resultDisplay', $data);
    
    	}
    }

    Now, you are ready to test the application.


 

Testing the Hello World! application

  1. Go to your browser (chrome in my case) and go to the following address (or the correct address according to your own setup)
    http://localhost/tutorial/1_hello_world/helloworld
  2. You will see the following on the browser
  3. Press the “Submit a Request to model” button and you will go to the following link
    http://localhost/tutorial/1_hello_world/helloworld/requestModel
  4. At this point, you will be seeing this output,
  5. At this point, you can press back to start over.

You can now see that your application can retrieve data from database. This is it! the tutorial is complete!


Conclusion

You have learnt how to create a complete MVC application using CodeIgniter complete with the database. You now have the knowledge required to learn and develop more advanced web applications.

If you found my post helpful or have any questions, please leave a comment. [button link=”https://www.facebook.com/ubaaconsultants” type=”small” newwindow=”yes”] Facebook[/button] [button link=”https://twitter.com/Codeonion” type=”small” newwindow=”yes”] Twitter[/button]

If you think that there is something missing, or you would like me to add something or even, if you wish to request a tutorial, just let me know and I will make a tutorial just for you.

Back to CodeIgniter Tutorials