为 foreach() show.blade.php 问题提供的参数无效

当我单击我的 cms 中的帖子块时,出现错误。


这是 PostsController.php 的代码


<?php


namespace App\Http\Controllers\Blog;


use App\Http\Controllers\Controller;

use App\Post;

use Illuminate\Http\Request;

use App\Tag;

use App\Category;



class PostsController extends Controller

{

    public function show(Post $post) {

        return view('blog.show')->with('post', $post);

    }


    public function category(Category $category) {


        return view('blog.category')

        ->with('category', $category)

        ->with('posts', $category->post()->searched()->simplePaginate(3))

        ->with('categories', Category::all())

        ->with('tags', Tag::all());

    }


    public function tag(Tag $tag) {

        return view('blog.tag')

        ->with('tag', $tag)

        ->with('categories', Category::all())

        ->with('tags', Tag::all())

        ->with('posts', $tag->posts()->searched()->simplePaginate(3));

    }

}

这是 Post.php 模型的代码


    <?php


namespace App;


use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;


use Illuminate\Support\Facades\Storage;

use App\Category;


class Post extends Model

{

    use SoftDeletes;


    protected $fillable = [

        'title', 'description', 'content', 'image', 'published_at', 'category_id', 'user_id',

    ];

/**

 * Delete post image from storage

 * HHE

 * @return void

 */

    public function deleteImage() {

       Storage::delete($this->image);

    }


    public function category() {

        return $this->belongsTo(Category::class);

    }


    public function tag() {

        return $this->belongsToMany(Tag::class);

    }


    /**

     *

     * @return bool

     */


    public function hasTag($tagId) {

        return in_array($tagId, $this->tags->pluck('id')->toArray());

    }


    public function user() {

        return $this->belongsTo(User::class);

    }


    public function scopeSearched($query) {

        $search = request()->query('search');


        if (!$search) {

            return $query;

        }


        return $query->where('title', 'LIKE', "%{$search}%");

    }

}


胡说叔叔
浏览 114回答 2
2回答

一只斗牛犬

我看不到您定义的任何函数(方法)或属性tags。在您的Post模型中,您有 method&nbsp;tag,但没有tags.您应该定义新方法或重命名该方法。

蝴蝶刀刀

我认为你正在尝试获取特定帖子的标签。因此,由于在您的模型帖子中与标签有关系这应该可以解决问题&nbsp;<div class="gap-xy-2 mt-6">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @foreach($post->tags->first() as $tag)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a class="badge badge-pill badge-secondary" href="{{ route('blog.tag', $tag->id) }}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{ $tag->name }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; &nbsp; &nbsp; </div>
打开App,查看更多内容
随时随地看视频慕课网APP