Laravel Custom Insert Query Example

Laravel 8 , Laravel 7 , Laravel , Laravel 6

Nicesnippets

3873

20-05-2021


Laravel Custom Insert Query Example

Hi Guys,

In this blog, I would like share with you custom insert query example in laravel. We will show laravel custom insert query example. We can insert the record using the DB facade with insert method.

In this example i am going to show you how to insert data in database using laravel framework PHP. The INSERT INTO statement is used to insert new data to a MySQL table:

Here I will give you full example and syntax for laravel custom insert query example. So let's see the bellow example:

Syntax


DB::insert('insert into table_name (column_name, column_name) values (?, ?)', [value_1, 'value_n']);

Add Route

In this step, you can add route in routes file so let's open web.php file add bellow route in file.

routes/web.php

use App\Http\Controllers\StudentInsertController;

Route::get('insert','[email protected]');

Route::post('create','[email protected]');

Create Controller

In this step you have to need new controller as StudentInsertController so let's open terminal and run bellow artisan command:

php artisan make:controller StudentInsertController

App\Http\Controllers\StudentInsertController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class StudentInsertController extends Controller

{

public function insertform()

{

return view('student_create');

}

public function insert(Request $request)

{

$name = $request->input('student_name');

DB::insert('insert into student (name) values(?)',[$name]);

echo "Record inserted successfully.<br/>";

echo '<a href = "/insert">Click Here</a> to go back.';

}

}

Create View File

In the last step, you can create view file as studentCreate.blade.php file open this file put the bellow code:

<html>

<head>

<title>Laravel Custom Insert Query - Nicesnippets.com</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<style type="text/css">

body{

background:#df6d6d;

}

.main-box{

padding:20px;

margin-top:150px;

background: #fff;

margin-left:150px;

}

</style>

</head>

<body>

<div class="container">

<div class="row">

<div class="col-md-8 main-box">

<h2>Laravel Custom Insert Query - Nicesnippets.com</h2>

<form action = "{{ route('create') }}" method = "post" class="mt-4">

<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">

<div class="form-group">

<label>Name</label>

<input type='text' class="form-control" name='student_name'/>

</div>

<div class="form-group">

<input type='submit' class="btn btn-success" value="Add student"/>

</div>

</form>

</div>

</div>

</div>

</body>

</html>

It will help you....


Recommended Posts