Eloquent: relationships between tables in a blog

1

One 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 
    
asked by anonymous 23.01.2017 / 02:27

1 answer

1

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

Using the hasMany(); method, which you can put in 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);
    }

}

Ok, now how do you access this method? Simple, create an object of category type, 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 handle the 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

Done, this retornaTodosOsPostsDessaCategoria() method returns a collection of objects, where you can manipulate them any way you want.

    
08.02.2017 / 14:45