Home > Back-end >  How to make route in laravel using GET Page?
How to make route in laravel using GET Page?

Time:12-29

Before using laravel, usually I route my page using code like this:

//index.php
$get_page=$_GET['page'];
if (empty($get_page) or $get_page=='dashboard')
{
   include ('content/dashboard.php');   
}elseif ($get_page=='schedule')
{
  include ('content/schedule.php');
}

else{
    include ('404/404.php');
}

Is there anyway that I can route my page like that but in Laravel? I prefer to use format : www.example.com/?page=schedule rather than www.example.com/schedule

CodePudding user response:

Route::get('/', function (Request $request) {
    if($request->query('page')) {
        $page = $request->query('page');
        return view($page);
    }
});

Documentation: https://laravel.com/docs/8.x/routing

CodePudding user response:

You can try this in your controller

public function index(Request $request): JsonResponse
    {
        $routeName = $request->get('page');
        try {
            if (isset($routeName))
            {
                return redirect(route($routeName));
            }
            return abort(404);
        } catch (Exception $exception) {
            return abort(404);
        }

    }

And use named routes like these

Route::get('dashboard', [DashboardController::class, 'dashboard'])->name('dashboard');

CodePudding user response:

So now my route on laravel are like this:

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request; //have to use this

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

/* Route::get('/', function () {
    return view('index');
});
 */

Route::get('/', function (Request $request) {
    if($request->query('page')) {
        $page = $request->query('page');
        return view($page);
    }else{
        return view('index');
    }
});

It works really well!

CodePudding user response:

laravel is only farmwork of PHP. so it is similar

write this code on your blade.

@php  $get_page=$_GET['page']; @endphp

@if (empty($get_page) or $get_page=='dashboard')
     @include('content.dashboard.php');
@elseif ($get_page=='schedule')
     @include ('content.schedule.php');
@elseif
    @include ('404.404.php');
@endif
  • Related