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
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();
}
3
Answers
In this case you have to pass the table name too.
I use a pivtot table for my application to simply be able to link multiple users to a task. However I do not use a model for my pivot table.. I don’t think it is needed, you just need to migration table,
This is what I have.. If you did this it will simply save a user and your file when you attach a user.. if this function has the download too you could just check for the users on that file(they will have downloaded it)
you could go
And this would get your downloads (or make a scope for this since it will be easier to read)
I hope this helps!
to work with pivot table in laravel, you most likely choose between 2 things: the
pivot
method and making a Pivot Model:First solution: pivot method:
+File Model (i will only put the relationship method here):
+User Model:
+How to use:
Second solution: pivot Model
+Download Model
+User Model:
+File Model: