Support the ongoing development of Laravel.io →
Database Eloquent

Just a quick one, i'm struggling to do relationships correctly..

I have 2 tables 'users' and 'files'.

Users can upload files so one user will have many files

so in my User model i have added:

  public function files()
  {
      return $this->hasMany('File');
  }

and un the File model:

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

Is that correct?

I'm not sure what is the best way to grab the user id.. when a user adds a file an entry will be saved into the file database, to correctly link files to a user i have added a user_id entry to the table, how can i get the user id from the User model to place into user_id field on the files Model?

I'm not sure the correct markup to grab the user id from the files controller.. When a user uploads a file it saves an entry into the database.. I need to grab the users user_id so that it is correctly assigned

Last updated 3 years ago.
0

First you need to find user id, and add user id to files table. You should try something like this:

$user = User::find(1);
$user_id = $user->id;

// now that you get user id add it to Files:

$file = new Files();
$file->user_id = $user_id;
...
$file->save();

Or if you use Sentry you can get user ID by


$user = Sentry::getUser();
$user_id = $user->id;

Later you can access user files by:

$user = User::find(1);
$user->files;
Last updated 3 years ago.
0

Thanks for that but i'm still struggling. how should i be pulling in the user id? in your example the ID is hard coded.

in my files model i have tried the following:

      {
      	$object = new Object;
	$object->user_id = Auth::user()->id;
	$object->hash = 'testing';
	$object->file = 'some-file-name.jpg';
	$object->save();
      }

but it fails. if i hard code the userid it works:

$object->user_id = '1';

Last updated 3 years ago.
0

Are you logged in? If you are not logged in than Auth::user()->id is probably NULL.

Try to first check with "Auth::check()" is user logged in.

Last updated 3 years ago.
0

Yes i've done an Auth check it's not working. I can access Auth::user()->id from the view but not a controller.

As a quick fix i'm saving the ID in the form, then when posted is passed back to the controller but i would ideally like to be able to grab the users id straight from the controller.

Last updated 3 years ago.
0

looks like your relationships are inverted. Should be

public function files() { return $this->belongsTo('User'); return $this->hasMany('File'); }

public function user() { return $this->hasMany('File'); } }

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.