I am attempting to return which user posted a comment, along with the time they posted the comment.
I have a model for comments
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
protected $guarded = [];
public function adjustments()
{
return $this->belongsToMany(User::class, 'adjustments')
->withTimestamps();
}
}
A pivot table which tracks which users posted which comments
public function up()
{
Schema::create('adjustments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->unsignedInteger('comments_id')->index();
$table->timestamps();
});
}
An empty adjustments model
use Illuminate\Database\Eloquent\Model;
class adjustment extends Model
{
//
}
In php artisan tinker
when $comment = App\comment::first();
and $user = App\user::first();
I'm able to successfully attach a user_id to a comment_id using $comment->adjustments()->attach($user->id)
and calling App\adjustments::all();
will correctly return
=> Illuminate\Database\Eloquent\Collection {#2935 all: [ App\adjustment {#2941 id: 1, user_id: 1, comments_id: 1, created_at: "2019-11-16 17:05:10", updated_at: "2019-11-16 17:05:10", }, ], }
When I'm trying to show the adjustments in my view, I get an empty list.
@foreach ($comment->adjustments as $user)
<li> on </li>
@endforeach
In my products controller (a user makes comments on products) I have the following code in my show function
public function show(products $product, comments $comment, User $user)
{
return view ('products.show', compact('product'), compact('comment'));
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire