Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel attach data to pivot table

So i am working on a laravel project with multiple table’s and pivot table’s but i cant attach data to a specific pivot table because it wont accept the name.
as a user i want to be able to download files from the ‘file’ crud. That works. but after i downloaded i want to be able to see who downloaded what file as an admin, this does not work

the query i get is:INSERT INTO file_user (file_id, user_id) VALUES (7, 2)

i basically want to change the: file_user to download. but i have no idea how to do that without making a full query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

table ‘file’

  • id
    -name
    -file (document)

table ‘user’
-id
-name
-username
-role

pivot table ‘download’
-id
-file_id
-user_id

user model:

 public function role(){
        return $this->belongsTo(Role::class,'role_id');
    }
    public function file(){
        return $this->belongsToMany(File::class);
    }
    

file model:

   public function user(){
        return $this->belongsToMany(User::class);
    }
    

    protected $table = 'file';

download model (pivot)

  protected $table = 'download';
    protected $fillable = [
        'file_id',
        'user_id',
    ];

    public function file() {
        return $this->belongsTo('file');
    }

    public function user() {
        return $this->belongsTo('users');
    }

controller:

 public function download(Request $request, int $fileId)
    {
        $id = Auth::user();
        $fullfile = File::find($fileId);
       
        $downloadfile = File::find($fullfile, ['file'])->pluck('file')->last();

       // return response()->download($downloadfile);
       dd($fullfile->user()->attach($id));
        return back();
    }

>Solution :

In this case you have to pass the table name too.

public function file(){
    return $this->belongsToMany(File::class, 'download');
}
   public function user(){
    return $this->belongsToMany(User::class, 'download');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading