Alguém teria um exemplo prático de uso de relacionamentos no Eloquent da seguinte forma:
Tenho um blog com várias categorias, nessas categorias vou ter vários Posts, como eu faço para exibir uma categoria com vários Post na Views.
Já vi vários exemplos aqui, mas nenhum se encaixou no que eu quero acima.
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
$posts = Category::find(1)->posts()->orderBy('created_at', 'desc')->get();
. tenta ai.