Pass variable into Laravel {{ route }} helper

I have routes for /admin/login and also for /user/login

I'm looking for both of the views to share the same layout file and so looking to pass the first segment (admin or user) into the route helper.

Is that possible?

So effectively, I'd be looking to do something like:

{{ route($thisIsDynamic.'.login') }}

where $thisIsDynamic would either be admin or user depending on the URL.

3 answers

  • answered 2018-02-13 02:55 Kasnady

    route only can contain of route name. If you want to pass link, you should use URL::

    {{ URL::to($thisIsDynamic.'login') }}
    

    Refer this: Laravel blade templates, foreach variable inside URL::to?

  • answered 2018-02-13 02:57 Jonjie

    Based on my understanding, you may try using a wild card and passing the data into the URL like so:

    routes

    Route::get('/login/{type}', function($type){
      return view('login', compact('type'));
    });
    

    You can now have access on the $type variable on the view.

    Now, if you want to access the route, just add it a name then pass the $type on it.

  • answered 2018-02-13 05:47 p01ymath

    I don't recommend redirection based on route names when they are dynamic. But if you really want to do that, Here is how you do it.

    Route::get('admin/login',"SomeController@someMethod")->name('admin-login');
    Route::get('user/login',"SomeController@someMethod2")->name('user-login');
    

    And, whenever you want to pass by name, you can do this {{ route("$thisIsDynamic-login") }}. But, As I said, this is not the right way to do this. Here is how you can do it the right way.

    Web.php

    Route::get('{type}/login',function(){
        return view('login')->with('type',$type);
    });
    

    login.blade.php (Just an example of how you do it)

    @extends('layout.you.want.to.extend')
    
    @section('content')
        @if($type == 'user')
            // User login form
        @else
            // Admin login form
        @endif
    @endsection
    

    I assume this is what you want to do. Let me know if I misunderstood anything or if you have any more queries.