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:
Controllers
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(Request $request)
{
$request->session()->flash('msg1', 'abc');
$request->session()->flash('msg2', 'def');
return redirect('/demo/index2');
}
public function index2(Request $request)
{
if ($request->session()->has('msg1')) {
echo 'msg1: ' . $request->session()->get('msg1').'<br>';
}
return view('demo/index');
}
}
Views
Create new folder named demo in resources/views folder. In this folder, create new Blade file named index.blade.php as below:
<html>
<html>
<head>
<title>Laravel</title>
</head>
<body>
@if(Session::has('msg1'))
msg1: {{session('msg1')}}
<br>
@endif
@if(Session::has('msg2'))
msg2: {{session('msg2')}}
@endif
<h3>Index</h3>
</body>
</html>
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/index2', [DemoController::class, 'index2']);
});
Structure of Laravel Project
Run Application
Access index action in Demo controller with url http://localhost:8000/demo/index to create new sessions and redirect to index2 action in Demo controller with url http://localhost:8000/demo/index2
Output