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();
– JuniorNunes
I am wanting to display in the view the posts of only one category...
– Helio
And apparently you’re doing it right:
$posts = Category::find(1)->posts()->orderBy('created_at', 'desc')->get();
. try it there.– JuniorNunes