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

时间:2019-07-17 21:05:41

标签: php laravel laravel-5.8

我试图显示帖子创建者的名字,但我有一个错误

@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');
    }
}

ProfileController

<?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]);
    }
}

PostController

<?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)

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

1 个答案:

答案 0 :(得分:0)

问题是此行$ 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