How to insert data into a database using Laravel and Ajax

 To insert data into a database using Laravel and Ajax, you can follow these steps:


Step 1: Create a Route Create a route in your Laravel application that will handle the Ajax request. This route should point to a controller method that will insert the data into the database.

Step 2: Create a Controller Create a controller in your Laravel application that will handle the Ajax request. This controller should have a method that will insert the data into the database.

Step 3: Create a View Create a view in your Laravel application that will contain the form or input fields that will capture the data to be inserted into the database.

Step 4: Create an Ajax Request Create an Ajax request in your view that will send the data to the controller method when the form is submitted.

Step 5: Insert the Data into the Database In the controller method, use the Laravel Eloquent ORM to insert the data into the database.

Here is a sample code for inserting data into the database using Laravel and Ajax:

Route:


Route::post('/insert-data', 'DataController@insertData');

Controller:



use Illuminate\Http\Request;
use App\Models\Data;

class DataController extends Controller
{
public function insertData(Request $request)
{
$data = new Data;
$data->name = $request->name;
$data->email = $request->email;
$data->save();

return response()->json(['success'=>'Data is successfully added']);
}
}


View:


<form>
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<button type="button" onclick="insertData()">Submit</button>
</form>

<script>
function insertData() {
var name = $('#name').val();
var email = $('#email').val();

$.ajax({
type: 'POST',
url: '/insert-data',
data: {
name: name,
email: email,
_token: '{{ csrf_token() }}'
},
success: function(data) {
alert(data.success);
}
});
}
</script>


Note: In the above code, we are using jQuery for sending the Ajax request. Also, make sure to include the CSRF token in the Ajax request.

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...