dongshi1914 2016-01-28 06:55
浏览 27
已采纳

如何从博客Laravel 5.2获取用户名

I made a blog in Laravel 5.2. I'am having trouble displaying a username associated with that blog. My flyers are linked with a user_id, but I cant get the actual username of the flyer created.

Here is my User relation with Flyer:

/**
* One user can have many Travel Flyers.
*/
    public function travelFlyers() {
        return $this->hasMany(TravelFlyers::class);
    }

Here is my Flyer model associating a user:

/**
     * A Travel Flyer belongs to a user.
     */
    public function user() {
        return $this->belongsTo('App/User', 'user_id');
    }

Here is my show method for displaying flyers:

 /**
     * Show a Travel Flyer in detail.
     * -- with title being the url
     */
    public function show($title) {
        //
        $travelFlyer = TravelFlyers::TravelFlyerLocatedAt($title);

        // return a view with the travel Flyer.
        return view('travelflyers.show', compact('travelFlyer'));
    }

And here is my flyer_table:

public function up()
    {
        Schema::create('travel_flyers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->string('excerpt');
            $table->text('description');
            $table->string('country');
            $table->string('state');
            $table->string('city');
            $table->double('lat', 20, 10);
            $table->double('lng', 20, 10);
            $table->timestamps();
            $table->timestamp('published_at');
        });
    }

I need to do something like this:

        @foreach($travelFlyers as $flyer)
            <div class="col-md-12">
                <p><b>Username:</b> {{ $flyer->username }}</p>
            </div>
        @endforeach


        This works fine, but I need username, not ID

         @foreach($travelFlyers as $flyer)
            <div class="col-md-12">
                <p><b>Username:</b> {{ $flyer->user_id }}</p>
            </div>
        @endforeach
  • 写回答

1条回答 默认 最新

  • dongshan4316 2016-01-28 07:13
    关注
    {{ $flyer->username }}
    

    A flyer has no username, a user has a username. But what flyer has is a user, so you need to use

    {{ $flyer->user->username }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?