so i have a code that show all my product
@foreach($products as $product)
<div class="col-lg-4 col-md-4 col-sm-6 col-12 event-item-col ">
<div class="card card-event info-overlay">
<div class="img has-background h-50">
<div class="pop-info ">
<span class="event-badges ">
<span class="badge price-tag big badge-default"></span>
</span>
</div>
<a href="/product/" class="event-pop-link">
<span class="event-badges ">
<span class="badge badge-danger"> if he buy</span>
</span>
<div class="event-pop-info">
<p class="badge"></p>
<p class="publisher">by <strong><?php $id = $product->user_id; $users = $user->findOrFail($id); echo $users->first; ?> <?php echo $user->last ?></strong></p>
</div>
</a>
<a href="event-details.html">
<img alt="340x230" class="card-img-top img-responsive h-100" data-holder-rendered="true" src="image/products/product.jpg"> </a>
</div>
<div class="card-body h-50">
<h4 class="card-title">
<a href="/product/"></a>
</h4>
<p class="card-tex" style="overflow: hidden"></p>
<div class="card-event-info">
<p class="event-location"><i class="fas fa-location-arrow"></i>
<a class="location" href="/user/product/"><?php echo $users->first; ?> <?php echo $user->last ?></a></p>
<p class="event-time"><i class="fas fa-calendar-alt"> </i></p>
</div>
</div>
</div>
</div>
@endforeach
and this is my controller
public function index()
{
$user = User::find(1);
$products = product::orderBy('created_at', 'desc')->Paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null);
return view('welcome', compact('products', 'user'));
}
like you can see in my view i have this code
<?php $id = $product->user_id; $users = $user->findOrFail($id); echo $users->first; ?> <?php echo $user->last ?>
that make me able to get the name of the user that create this product ,product and user table have one to many relations.i want to change this code to a better and smaller code.
product->user->first
dont work. i tried it so many ways but that just dont work. if anyone can help me to get data with laravel way i will be greatfull.(sry if my question is duplicate, I tried so many ways but didn't work ) to give u guys more info this is my class
class User extends Authenticatable
{
use Notifiable;
use Friendable;
protected $fillable = [
'first','last', 'email', 'password','phone','question','answer','description',
];
protected $hidden = [
'password', 'remember_token',
];
public function products()
{
return $this->hasMany(Product::class);
}
}
and product class :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product extends Model
{
protected $fillable = [
'part_id', 'smalldescription', 'description', 'pname', 'link', 'price',
];
public function users()
{
return $this->belongsTo(User::class);
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire