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:
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 redirect('/demo/index2');
}
public function index2()
{
return view('demo/index');
}
public function index3()
{
return redirect()->route('redirectWithQueryString', ['id' => 123, 'username' => 'acc1']);
}
public function index4(Request $request)
{
if ($request->has('id')) {
$id = $request->get('id');
echo 'id: ' . $id;
}
if ($request->has('username')) {
$username = $request->get('username');
echo '<br>username: ' . $username;
}
return view('demo/index');
}
}
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>
</head>
<body>
<h3>Index</h3>
</body>
</html>
Create Routes
Open web.php file in routes folder, add new routes as below:
<?php
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/index2', [DemoController::class, 'index2']);
Route::get('/demo/index3', [DemoController::class, 'index3']);
Route::get('/demo/index4', [DemoController::class, 'index4'])->name('redirectWithQueryString');
});
Structure of Laravel Project
Run Application
Access index action in Demo controller with http://localhost:8000/demo/index will redirect to link http://localhost:8000/demo/index2
Output
Access index3 action in Demo controller with http://localhost:8000/demo/index3 will redirect to link http://localhost:8000/demo/index4?id=123&username=acc1
Output