Skip to content

Instantly share code, notes, and snippets.

@uno-de-piera uno-de-piera/Post.php Secret
Last active Jun 12, 2019

Embed
What would you like to do?
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $guarded = ['id'];
public function user () {
return $this->belongsTo(User::class);
}
}
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts () {
return $this->hasMany(Post::class);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function show ($id) {
$user = User::findOrFail($id);
foreach ($user->posts as $post) { //error, ¡cada post que exista es 1 consulta a base de datos!
}
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function show ($id) {
$user = User::with('posts')->findOrFail($id);
foreach ($user->posts as $post) { //ahora sí, ¡gracias al método with no tenemos consultas duplicadas!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.