Eloquent: relationships between blog tables

Asked

Viewed 873 times

1

Someone would have a practical example of using relationships in Eloquent as follows:

I have a blog with several categories, in these categories I will have several Posts, as I do to display a category with several Post in Views.

I’ve seen several examples here, but none fit what I want above.

Model Post:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function tags()
    {
        return $this->belongsToMany('App\Tag');

    }

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

Model Category:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

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

View index

<div class="col-sm-6">
  <div id="home-slider">
    @foreach($posts as $post)
    <div class="post feature-post">
      <div class="entry-header">
        <div class="entry-thumbnail">
          <img class="img-responsive" src="{{ asset('imgs/'.$post->image) }}" width="572" height="350" alt="" />{{--
          <img class="img-responsive" src="{{ asset('public/imgs/'.$post->image) }}" width="572" height="350" alt="" />--}}</div>
        <div class="catagory world"><a href="#">{{ $post->category->name }}</a>
        </div>
      </div>
      <div class="post-content">
        <h2 class="entry-title">
          <a href="{{ route('posts.show', $post->id) }}">{{ $post->title }}</a>
        </h2>
      </div>
    </div>
    <!--/post-->
    @endforeach
  </div>
</div>

Controller:

<?php 

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Post;
use Mail;
use Session;
use App\Category;

class PagesController extends Controller {

    public function getIndex() {

        $posts = category::find(1)->posts()->orderBy('created_at', 'desc');
        return view('v1.index')->withPosts($posts);
        // $posts = Post::orderBy('created_at', 'desc')->limit(3)->get();
        // $categorias = Category::find(1);
        // return view('v1.index')->withPosts($posts)->withCategorias($categorias);
    }


    public function getContact() {
        return view('v1.contato');
    }

    public function postContact(Request $request) {
        $this->validate($request, [
            'email' => 'required|email',
            'subject' => 'min:3',
            'message' => 'min:10']);

        $data = array(
            'email' => $request->email,
            'subject' => $request->subject,
            'bodyMessage' => $request->message
            );

        Mail::send('emails.contact', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to('[email protected]');
            $message->subject($data['subject']);
        });

        Session::flash('success', 'Your Email was Sent!');

        return redirect('/');
    }


}
laravel 
  • Is your code working? The relationships are apparently correct. I think after the orderby you need to give a ->get();

  • I am wanting to display in the view the posts of only one category...

  • And apparently you’re doing it right: $posts = Category::find(1)->posts()->orderBy('created_at', 'desc')->get();. try it there.

1 answer

1


Come on, the Eloquent has a way to list all data from other tables related to a particular model.

Using the method hasMany();, that you can put on the model, follow this practical example:

Model:

class Categoria extends Model
{
    protected $fillable = ['id', 'nome', 'descricao'];

    protected $table = 'categoria';

    public function retornaTodosOsPostsDessaCategoria()
    {
        return $this->hasMany(Post::class);
    }

}

Okay, now how do you access this method? Simple, create a category type object, or directly use the class.

class CategoriaController extends Controller
{
    public function __construct()
    {
        $this->categoria = new Categoria();
    }

    public function listaTodosOsPostsNaViewIndex($idCategoria)
    {
        return view('categoria.index', [
            'categoria' =>  $this->categoria->find($idCategoria),
            'posts' => $this->categoria->find($idCategoria)->retornaTodosOsPostsDessaCategoria()
            //retornar esse posts é facultativo, pois voce tem acesso ao método na view;
        ]);
    }

}

Now how to manipulate in view.

View

@extends('templates.app') 
@section('content')

<div class="ls-box">
  <table class="ls-table ls-table-striped ls-table-bordered">
    <thead>
      <tr>
        <th>Nome</th>
        <th style="text-align: center">Título</th>
      </tr>
    </thead>
    <tbody>
      @foreach($posts [pode usar tambem o $categoria->retornaTodosOsPostsDessaCategoria] as $post)
      <tr>
        <td class="ls-color-theme">{{$post->titulo}}</td>
      </tr>
      @endforeach
    </tbody>
  </table>
</div>
@endsection

All right, that method retornaTodosOsPostsDessaCategoria() returns a collection of objects, where you can manipulate the way you want.

  • 1

    Thanks @Felipe Paetzold

Browser other questions tagged

You are not signed in. Login or sign up in order to post.