Install Laravel
-
Download and install the latest version of Composer from https://getcomposer.org/download/
-
Open Windows Terminal in Visual Studio Code install Laravel Installer with command as below:
composer global require laravel/installer
-
Create new folder named LearnLaravelWithRealApps. Use Visual Studio Code open to LearnLaravelWithRealApps foler. In this folder, create new project named LearnLaravelWithRealApps with command as below:
laravel new LearnLaravelWithRealApps
-
Run LearnLaravelWithRealApps project with command as below:
php artisan serve
-
Open LearnLaravelWithRealApps project with url as below:
http://localhost:8000
Add JQuery Library
Create new folder named js in public folder. Copy JQuery library to public/js folder.
Create Controller
Create new PHP file named DemoController.php in app/Http/Controllers folder as below:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index()
{
return view('demo/index');
}
public function ajax(Request $request)
{
$fullName = $request->get('fullName');
return response()->json(array('msg' => 'Hello ' . $fullName));
}
}
Create View
Create new folder named demo in resources/views folder. In this folder, create new Blade file named index.blade.php as below:
<html>
<head>
<title>Laravel</title>
<script src="{{asset('js/jquery-3.6.0.min.js')}}" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#buttonDemoAjax').on('click', function() {
var fullName = $('#textBoxFullName').val();
$.ajax({
type: 'GET',
data: {
fullName: fullName
},
url: "{{url('/demo/ajax')}}",
success: function(data) {
$('#result').html(data.msg);
}
});
});
});
</script>
</head>
<body>
<h3>Index</h3>
Full Name <input type="text" id="textBoxFullName">
<br>
<input type="button" value="Demo Ajax" id="buttonDemoAjax">
<br>
<span id="result"></span>
</body>
</html>
Create Routes
Open web.php file in routes folder, add new routes as below:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DemoController;
Route::group([], function () {
Route::get('/', [DemoController::class, 'index']);
Route::get('/demo', [DemoController::class, 'index']);
Route::get('/demo/index', [DemoController::class, 'index']);
Route::get('/demo/ajax', [DemoController::class, 'ajax']);
});
Structure of Laravel Project
Run Application
Access index action in Demo controller with urls as below:
- http://localhost:8000
- http://localhost:8000/demo
- http://localhost:8000/demo/index
Output
Input data and click Demo Ajax button to call ajax