mrmar
mrmar

Reputation: 803

Problem with displaying data with many to many relationship in Laravel

I have many to many relationship between users and products table, and I set up pivot table product_user with product_id, user_id columns. When I try and upload some file it uploads successfully to the database and it shows data on page, but it doesn't show column 'owner of the product' which is column where is that relationship. Also when I manually update my database table product_user and set correct ids and refresh page then 'owner of the product' column shows correct information. I would like to display that information when I upload file dynamically without manually updating the database. I tried with attach method but for some reason it won't work. Any help is appreciated Here is my code:

HomeController:

<?php

namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    public function store(Request $request)
    {
        if ($file = $request->file('files')) {
            $name = $file->getClientOriginalName();
            if ($file->move('products', $name)) {
                $product = new Product();
                $product->files = $name;
                $product->save();
                $product->users()->attach($request->user_id);

                return redirect()->route('welcome');
            }
            return redirect()->back();
        }
    }
}

welcome.blade.php:

@if($products)
<table class="table">
    <thead>
        <th>#</th>
        <th>Product Name</th>
        <th>Owner Of The Product</th>
        <th>Created At</th>
    </thead>
    <tbody>
    @foreach ($products as $product)
         <tr>
             <td>{{ $product->id }}</td>
             <td>{{ $product->files }}</td>
             <td>
                 @foreach ($product->users as $user)
                     {{ $user->name }}
                 @endforeach
             </td>
             <td>{{ date('M j, Y', strtotime($product->created_at)) }</td>
         </tr>
    @endforeach
    </tbody>
 </table>
 @endif

home.blade.php:

<div class="col-md-12">
    <form action="/store" method="POST" enctype="multipart/form-data">
        {{ csrf_field() }}
        <div class="form-group">
            <input type="file" name="files" class="form-control">
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-success" value="Submit">
        </div>
     </form> 
 </div>

User.php:

<?php

namespace App;

use App\Product;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
    'name', 'email', 'password',
    ];

    protected $hidden = [
    'password', 'remember_token',
    ];

    protected $casts = [
    'email_verified_at' => 'datetime',
    ];

    public function products()
    {
        return $this->belongsToMany(Product::class, 'product_user', 'user_id', 'product_id');
    }
}

Product.php:

<?php
namespace App;

use App\User;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['files'];

    public function users()
    {
        return $this->belongsToMany(User::class, 'product_user', 'product_id', 'user_id');
    }
}

Upvotes: 2

Views: 183

Answers (1)

Thomas
Thomas

Reputation: 8849

The request has no user_id property if you don't submit a field with that name.

You have a couple of options to get the current user's ID. My choice would be Auth::id() or auth()->id since those don't load the user model from the database.

More methods of getting the user ID: how to get current user id in laravel 5.4

Upvotes: 1

Related Questions