Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year 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 1 year 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 1 year 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 1 year 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 1 year 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 1 year ago.
0

Sign in to participate in this thread!

Eventy

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.

© 2024 Laravel.io - All rights reserved.