简体   繁体   中英

Laravel return variable in blade template

I have a route like below.

Route::get('profile/{username}', 'ProfileController@index');

ProfileController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class ProfileController extends Controller
{
    function index() {
        view('profile.index');
    }
}

profile/index.blade.php

{username}

But it doesn't echo the username when I go to /profile/salep , what's missing here?

If I change my ProfileController to this (below), it works but PhpStorm says "Unreachable stamement" for the view.

class ProfileController extends Controller
{
    function index($username) {
        return $username;
        view('profile.index');
    }
}

I didn't use the structure below (took it from the documentation) because I need to pass my variable to a view rather than returning, so I need to both return and pass it to a view, I guess.

Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

You were nearly there with the second attempt.

Try this:

class ProfileController extends Controller
{
    function index($username) {
        return view('profile.index')->with('username', $username);
    }
}

I solved it.

routes.php

Route::get('profile/{username}', 'ProfileController@index');

ProfileController.php

class ProfileController extends Controller
{
    function index($username) {
        return view('profile.index')->with('username', $username);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM