laravelroutesgetmethod

How to pass value in URL in Laravel


I want to click on "View Detail" button and go to another page "/viewdeail/id=2", here id=2 is comes from the View Detail button click. So far I prepare this snippet.

Controller:

public function schooldetailviewid($school_id)
     {
        return view('viewdeail/school_id={$school_id}', compact('school_id'));
     }

Route

Route::get('/viewdeail/school_id={school_id}', 'ViewController@schooldetailviewid')->name('schooldetail');

I am very much confused about how to solve this.


Solution

  • With Laravel, if you need to pass a required parameter in your route, you need to specify it into your routes/web.php file, and get it from your controller action.

    This the common way to do that:

    // routes/web.php
    
    Route::get('/viewdeail/{schoolId}', 'ViewController@details')->name('schooldetail');
    
    // app/Http/Controllers/ViewController.php
    
    class ViewController extends Controller {
    
        ...
    
        public function details($schoolId) {
            // your view located in ressources/views folder
            return view('viewdeail/', compact('schoolId'));
        }
    
    }
    

    Now, if you want to just get parameters like domain.tld/viewdeail?schoolId=3 for example, you need to remove {schoolId} in the previously defined route in the routes/web.php file, and edit your controller and proceed like that:

    // app/Http/Controllers/ViewController.php
    
    use Illuminate\Http\Request; // we need the Request class, so import it
    
    class ViewController extends Controller {
    
        ...
    
        public function details(Request $request) {
            $schoolId = $request->query('schoolId');
    
            // your view located in ressources/views folder
            return view('viewdeail/', compact('schoolId'));
        }
    
    }