Materi08 Framework-Web Db-Insert

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Working With Database

Laravel has made processing with database very easy. Laravel currently supports following 4 databases
• MySQL
• Postgres
• SQLite
• SQL Server
The query to the database can be fired using raw SQL, the fluent query builder, and the Eloquent ORM.
To understand the all CRUD (Create, Read, Update, Delete) operations with Laravel, we will use simple
store management system.

Connecting to Database
In this material, MySQL is used as an example configuration. For this material required php7.2-mysql (or
php-pdo-mysql). Initial database configuration on a laravel system can be done via the environment file
.env file or the config/database.php file. If you want to use the environment file .env, configure it as
follows (For example, we will manage storedb database)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=storedb
DB_USERNAME=xxxx
DB_PASSWORD=yyyy
If you want to use config/database.php file, the DB_** environtment variables must be disabled. Put a
hash # in front of the variable. Configure config/database.php as follows..
'connections' => [
. . . . . . . . .
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'storedb'),
'username' => env('DB_USERNAME', 'xxxx'),
'password' => env('DB_PASSWORD', 'yyyy'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
. . . . . . . . .
],
Note the writing in red, storedb is database name, xxxx is username and yyyy is password. please arrange
yourself as desired.
Assume you have access to MySQL server with user xxxx and password yyyy with database name
storedb. Now Login to mysql server and write the following commands
use storedb;
CREATE TABLE consumer (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(35) NOT NULL,
address varchar(35) NOT NULL,
PRIMARY KEY (id)
);

Now you have consumer table with this structure


Column Type
id int(11) Auto Increment
name varchar(35)
address varchar(35)

We will see how to add, delete, update and retrieve records from database using Laravel in consumer
table.
No. Record & Description
Insert Records
1
We can insert the record using the DB facade with insert method.
Retrieve Records
2 After configuring the database, we can retrieve the records using the
DB facade with select method.
Update Records
3
We can update the records using the DB facade with update method.
Delete Records
4
We can delete the record using the DB facade with the delete method.
Insert Records
We can insert the record using the DB facade with insert method. The syntax of insert method is as
shown in the following table.
Syntax bool insert(string $query, array $bindings = array())
• $query(string) query to execute in database
Parameters
• $bindings(array) values to bind with queries
Returns bool
Description Run an insert statement against the database.

Example
Step 1 Execute the below command to create a controller called ConsumerInsertController
php artisan make:controller ConsumerInsertController
Step 2 After the successful execution of step 1, you will receive the following output

Step 3 Copy the following code to file (Note the writing in red)
app/Http/Controllers/ConsumerInsertController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;

class ConsumerInsertController extends Controller


{
public function insertform()
{
return view('consumer-create');
}

public function insert(Request $request)


{
$name = $request->input('name01');
$address = $request->input('address01');
DB::insert("insert into consumer (name,address) values(?,?)",[$name,$address]);
echo "Record inserted successfully.<br>";
echo '<a href = "/insert">Click Here</a> to go back.';
}
}
Step 4 Create a view file called resources/views/consumer-create.php and copy the following code in
that file.
<html>
<head><title>Consumer Insert</title></head>
<body>
<form action = "/create" method = "post">
<input type='hidden' name='_token' value ='<?php echo csrf_token(); ?>'>
Name : <input type='text' name='name01'><br>
Address : <input type='text' name='address01'><br>
<input type = 'submit' value = "Add Consumer">
</form>
</body>
</html>

Step 5 Add the following lines in routes/web.php.


Route::get('insert','ConsumerInsertController@insertform');
Route::post('create','ConsumerInsertController@insert');

Step 6 Visit the following URL to insert record in database.


http://localhost:8000/insert

Step 7 The output will appear as shown in the following image.

Check the database, whether the data actually entered the consumer table. Login to mysql server and
write the following commands
use storedb;
select * from consumer;
The result is
+----+-------------+------------+
| id | name | address |
+----+-------------+------------+
| 1 | Eden Hazard | Yogyakarta |
+----+-------------+------------+
1 row in set (0.00 sec)
additional topics:
If the view uses the bootstrap feature online, the resources/views/consumer-create.php file can be
replaced like this
</html>
<head>
<title>Consumer Insert</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<form action = "/create" method = "post">
<input type='hidden' name='_token' value ='<?php echo csrf_token(); ?>'>
<div class="form-group">
<label for="name">Name :</label>
<input type="text" class="form-control" name="name01">
</div>
<div class="form-group">
<label for="address">Address :</label>
<input type="text" class="form-control" name="address01">
</div>
<input type="submit" class="btn btn-default" value="Add Consumer">
</form>
</div>

</body>
</html>

if bootstrap has been installed in public/css, public/js and public/fonts, the resources/views/consumer-
create.php file can be replaced like this
</html>
<head>
<title>Consumer Insert</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<form action = "/create" method = "post">
<input type='hidden' name='_token' value ='<?php echo csrf_token(); ?>'>
<div class="form-group">
<label for="name">Name :</label>
<input type="text" class="form-control" name="name01">
</div>
<div class="form-group">
<label for="address">Address :</label>
<input type="text" class="form-control" name="address01">
</div>
<input type="submit" class="btn btn-default" value="Add Consumer">
</form>
</div>

</body>
</html>

You might also like