【问题标题】:Undefined property: stdClass::$username (View: /home/annonces/resources/views/welcome.blade.php)未定义属性:stdClass::$username(查看:/home/annonces/resources/views/welcome.blade.php)
【发布时间】:2019-07-17 21:05:41
【问题描述】:

我尝试显示帖子创建者的姓名,但出现错误

@section('content')
<div class="container" id="results">
        <div class="row justify-content-center">
        <div class="col-md-12" style="display: flex; flex-flow: row wrap;">

    @foreach ($posts as $post)
    <div class="col-md-3">
       <a href="{{ route('posts.show', ['post' => $post->id]) }}"> <img src="{{ asset('storage') . '/' . $post->image }}" class="w-100"></a>
      <div class="card-body">
        <h5 class="card-title">{{ $post->title }}</h5>
        <small>{{ Carbon\Carbon::parse($post->created_at)->diffForHumans() }}</small>
        <span>Publié par {{ $post->username }}</span>
        <p class="card-text">{{ $post->descriptionpost }}</p>
        <p class="card-text">{{ $post->price }}</p>
        <a href="{{ route('posts.show', ['post' => $post->id]) }}" class="btn btn-primary">Voir</a>
    </div>
</div>
@endforeach

后模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'nom', 'prenom', 'adresse', 'ville', 'codepostale', 'datedenaissance','email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        static::created(function ($user) {
        $user->profile()->create([
           'description' =>  $user->username
        ]);
        });
    }

    public function getRouteKeyName()
    {
        return 'username';
    }

    public function profile()
    {
        return $this->hasOne('App\Profile');
    }

    public function following()
    {
        return $this->belongsToMany('App\Profile');
    }

    public function posts()
    {
        return $this->hasMany('App\Post')->orderBy('created_at', 'DESC');
    }
}

配置文件控制器

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class ProfileController extends Controller
{
    public function show(User $user)
    {
        $follows = (auth()->user()) ? auth()->user()->following->contains($user->profile->id) : false;

        return view('profile.show', compact('user', 'follows'));
    }

    public function edit(User $user)
    {
        $this->authorize('update', $user->profile);
        return view('profile.edit', compact('user'));
    }

    public function update(User $user)
    {
        $this->authorize('update', $user->profile);
        $data = request()->validate([
            'description' => 'required',
            'image' => 'sometimes|image|max:3000'
        ]);

        if (request('image')) {
        $imagePath = request('image')->store('avatars', 'public');

        $image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
        $image->save();

auth()->user()->profile->update(array_merge($data,
    ['image' => $imagePath]
));
        } else {
            auth()->user()->profile->update($data);
        }

        auth()->user()->profile->update($data);

        return redirect()->route('profile.show', ['user' => $user]);
    }
}

后控制器

<?php

namespace App\Http\Controllers;

use App\Http\Requests\Poststore;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\DB;

class PostController extends Controller
{


    public function index()
    {
        $posts = DB::table('posts')->orderBy('created_at', 'DESC')->paginate(1000);

        return view('welcome',['posts'=> $posts]);
    }

    public function create()
    {
        return view('posts.create');
    }

    public function store()
    {
        $data = request()->validate([
            'title' => ['required', 'string'],
            'image' => ['required', 'image'],
            'price' => ['required', 'integer'],
            'descriptionpost' => ['required', 'string']
        ]);

        $imagePath = request('image')->store('uploads', 'public');

        $image = Image::make(public_path("/storage/{$imagePath}"))->fit(1200, 1200);
        $image->save();


        auth()->user()->posts()->create([
            'title' => $data['title'],
            'descriptionpost' => $data['descriptionpost'],
            'price' => $data['price'],
            'image' => $imagePath
        ]);

        return redirect()->route('profile.show', ['user' => auth()->user() ]);
    }

    public function show(Post $post)
    {
        return view('posts.show', compact('post'));
    }

    public function search(Request $request)
    {
        $words = $request->words;
        $posts = DB::table('posts')->where('title', 'LIKE', '%$words%')->orWhere('descriptionpost', 'LIKE', '%$words%')->orderBy('created_at', 'DESC')->get();

        return response()->json(['success' => true, 'posts' => $posts]);
    }
}

我的错误:

未定义属性:stdClass::$username(查看:/home/annonces/resources/views/welcome.blade.php)

这是我的模特帖子和用户。有谁知道如何解决这个问题?不知道问题出在哪里。

【问题讨论】:

  • 你能分享你的Post模型吗
  • 好的,有一刻我编辑我的帖子
  • 请同时分享您的控制器,如果$post 实际上是模型的一个实例,$post-&gt;username 将评估为 null,但是,因为您的错误消息表明它是一个 stdClass

标签: php laravel laravel-5.8


【解决方案1】:

问题是 $post->username 这一行,你试图访问不存在的帖子模型上的用户名,首先返回带有帖子的用户模型

$post=post::find($id);

并在您的视图中将 $user 传递给视图

@section('content')
<div class="container" id="results">
        <div class="row justify-content-center">
        <div class="col-md-12" style="display: flex; flex-flow: row wrap;">
@foreach ($posts as $post)
<div class="col-md-3">
   <a href="{{ route('posts.show', ['post' => $post->id]) }}"> <img src="{{ asset('storage') . '/' . $post->image }}" class="w-100"></a>
  <div class="card-body">
    <h5 class="card-title">{{ $post->title }}</h5>
    <small>{{ Carbon\Carbon::parse($post->created_at)->diffForHumans() }}</small>
    <span>Publié par {{ $post->user->username }}</span>
    <p class="card-text">{{ $post->descriptionpost }}</p>
    <p class="card-text">{{ $post->price }}</p>
    <a href="{{ route('posts.show', ['post' => $post->id]) }}" class="btn btn-
primary">Voir</a>
    </div>
</div>
@endforeach

【讨论】:

  • 没问题,因为所有工作都只有用户名不起作用:/
  • 你需要把它放在控制器@DenKot
猜你喜欢
  • 1970-01-01
  • 2020-12-28
  • 2021-11-12
  • 1970-01-01
  • 2018-07-10
  • 2021-10-17
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多