Answer the question
In order to leave comments, you need to log in
How to display post category in laravel?
Like on the main page, where pots are displayed, display the category of each post.
PostController code:
<?php
namespace App\Http\Controllers\Posts;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;
class PostController extends Controller
{
public function index()
{
$posts = Post::orderBy('updated_at', 'desc')->where('status', 1)->get();
$categories = \App\Category::categoryAll();
return view('posts.index', compact('posts', 'categories'));
}
public function view($id)
{
$post = Post::where('status', 1)->find($id);
$data = [
'post' => $post,
];
return view('posts.view', $data);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function post()
{
return $this->hasMany('App\Post', 'category_id');
}
public static function categoryAll()
{
return Category::get();
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function category()
{
return $this->hasOne('App\Category', 'id');
}
public static function latestPost()
{
return Post::orderBy('updated_at', 'desc')->where('status', 1)->limit(5)->get();
}
}
@extends('layouts.app')
@section('content')
<section class="posts">
<div class="jumborton">
<h1>Блог<span>.</span></h1>
</div>
@if (count($posts) > 0)
@foreach ($posts as $post)
<article class="post">
<div class="post-img"><a href="#"><img src="{{ asset('assets/img/' . $post->img) }}"></a></div>
<div class="post-text">
<h2>{{ $post->title }}</h2>
<p class="post-text-information"><span>Категория:</span> <a href="#">{{ $post->category->title }}</a> <span>{{ $post->updated_at }}</span> <a href="#">5 комментариев</a></p>
<p class="post-text-article">{{ $post->description }}</p>
<a class="btn" href="{{ url('post', ['id' => $post->id]) }}">Продолжить чтение</a>
</div>
</article>
@endforeach
@else
<h1>Постов пока нет!</h1>
@endif
<div class="pagination">
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">></a></li>
</ul>
</div>
</section>
@endsection
Answer the question
In order to leave comments, you need to log in
Try:
yes
public function category()
{
return $this->hasOne('App\Category', 'category_id');
}
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question