Im a software engineer and i need to create a email template, using a blade view in…
- User
Im a software engineer and i need to create a email template, using a blade view in laravel, that, has 2 inputs box inside, and the user if compile them, with a javascript function sends to my backend laravel, the parameters inside them. I need to write a log for testing of this values. Give me the entire code.
- Assistant
Sure! Below is the complete code to create a Laravel Blade view with two input boxes. When the user fills them and submits, a JavaScript function will send the data to your Laravel backend using AJAX. The backend will receive the data and write a log entry with the received values for testing.
1. Set Up the Route
In your
routes/web.phpfile, define a POST route to handle the AJAX request:<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\InputController; Route::post('/submit-inputs', [InputController::class, 'submitInputs'])->name('submit.inputs');
2. Create the Controller
Generate a new controller named
InputControllerif you haven't already:php artisan make:controller InputControllerIn
app/Http/Controllers/InputController.php, add thesubmitInputsmethod:<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class InputController extends Controller { public function submitInputs(Request $request) { // Retrieve the input values $input1 = $request->input('input1'); $input2 = $request->input('input2'); // Log the input values for testing Log::info('Received inputs:', ['input1' => $input1, 'input2' => $input2]); // Return a JSON response return response()->json(['message' => 'Inputs received successfully.']); } }
3. Create the Blade View
In your
resources/viewsdirectory, create a Blade template namedemail_template.blade.php:<!-- resources/views/email_template.blade.php --> <!DOCTYPE html> <html> <head> <title>Email Template</title> <!-- Include CSRF Token in a meta tag --> <meta name="csrf-token" content="{{ csrf_token() }}"> </head> <body> <h1>Email Template with Input Boxes</h1> <!-- Input Boxes --> <div> <label for="input1">Input 1:</label> <input type="text" id="input1" name="input1"> </div> <br> <div> <label for="input2">Input 2:</label> <input type="text" id="input2" name="input2"> </div> <br> <button id="submitBtn">Submit</button> <!-- JavaScript Function --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Set up AJAX with CSRF Token $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') } }); document.getElementById('submitBtn').addEventListener('click', function () { // Get the input values var input1 = document.getElementById('input1').value; var input2 = document.getElementById('input2').value; // Send the data to the backend using AJAX $.ajax({ url: '{{ route("submit.inputs") }}', type: 'POST', data: { input1: input1, input2: input2 }, success: function (response) { alert(response.message); }, error: function (xhr) { alert('An error occurred.'); } }); }); </script> </body> </html>
4. Display the Blade View
Set up a route to display the Blade view. In
routes/web.php, add:Route::get('/email-template', function () { return view('email_template'); });
5. Testing the Setup
-
Start your Laravel development server:
php artisan serve -
Navigate to http://localhost:8000/email-template in your browser.
-
Fill in the input boxes and click the Submit button.
-
An alert should show the message "Inputs received successfully."
-
Check the Laravel log file at
storage/logs/laravel.log. You should see an entry similar to:[YYYY-MM-DD HH:MM:SS] local.INFO: Received inputs: {"input1":"value1","input2":"value2"}
Complete Code Files
For convenience, here are the complete code files:
routes/web.php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\InputController; Route::get('/email-template', function () { return view('email_template'); }); Route::post('/submit-inputs', [InputController::class, 'submitInputs'])->name('submit.inputs');app/Http/Controllers/InputController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class InputController extends Controller { public function submitInputs(Request $request) { // Retrieve the input values $input1 = $request->input('input1'); $input2 = $request->input('input2'); // Log the input values for testing Log::info('Received inputs:', ['input1' => $input1, 'input2' => $input2]); // Return a JSON response return response()->json(['message' => 'Inputs received successfully.']); } }resources/views/email_template.blade.php
<!DOCTYPE html> <html> <head> <title>Email Template</title> <!-- Include CSRF Token in a meta tag --> <meta name="csrf-token" content="{{ csrf_token() }}"> </head> <body> <h1>Email Template with Input Boxes</h1> <!-- Input Boxes --> <div> <label for="input1">Input 1:</label> <input type="text" id="input1" name="input1"> </div> <br> <div> <label for="input2">Input 2:</label> <input type="text" id="input2" name="input2"> </div> <br> <button id="submitBtn">Submit</button> <!-- JavaScript Function --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Set up AJAX with CSRF Token $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') } }); document.getElementById('submitBtn').addEventListener('click', function () { // Get the input values var input1 = document.getElementById('input1').value; var input2 = document.getElementById('input2').value; // Send the data to the backend using AJAX $.ajax({ url: '{{ route("submit.inputs") }}', type: 'POST', data: { input1: input1, input2: input2 }, success: function (response) { alert(response.message); }, error: function (xhr) { alert('An error occurred.'); } }); }); </script> </body> </html>
Notes
-
CSRF Protection: Laravel's CSRF protection requires a token for POST requests. We include it in a meta tag and set it in AJAX headers.
-
AJAX Setup: We use jQuery for simplicity. Ensure jQuery is included in your project. If you prefer vanilla JavaScript or another library, you can adjust accordingly.
-
Logging: We use Laravel's built-in logging system. The logs are stored in
storage/logs/laravel.log. -
Route Naming: Using
route('submit.inputs')in the Blade template ensures that the URL is generated correctly, even if the route changes.
Alternative: Using Fetch API Instead of jQuery
If you prefer to use the Fetch API instead of jQuery, replace the JavaScript section in your Blade template with the following:
<!-- ... previous HTML ... --> <!-- JavaScript Function --> <script> document.getElementById('submitBtn').addEventListener('click', function () { // Get the input values var input1 = document.getElementById('input1').value; var input2 = document.getElementById('input2').value; // Get CSRF token from meta tag var csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); // Send the data to the backend using Fetch API fetch('{{ route("submit.inputs") }}', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken }, body: JSON.stringify({ input1: input1, input2: input2 }) }) .then(response => response.json()) .then(data => { alert(data.message); }) .catch((error) => { alert('An error occurred.'); console.error('Error:', error); }); }); </script> <!-- ... rest of HTML ... -->
Final Remarks
With this setup, you have a fully functional email template in Laravel with two input boxes. When the user fills them out and submits, the data is sent to the backend using a JavaScript function, and the backend logs the values for testing purposes.
Let me know if you need further assistance or additional features!
-