user13523236
user13523236

Reputation: 135

show data if you have user id - laravel

I am creating a data list and I print it with foreach, i would like it to display the data only if user_id matches the user_id reading the data. (previously I already have the user authentication created)

I want the users who enter to only see the data that contains their user_id.

enter image description here

I already made the relationship between the users table 'id' field with user_id

pass the data with:

  public function index()
{
    $servicios = App\Servicio::all();

    return view('home', compact('servicios'));
}

How do I show the data that corresponds to the user_id of each one without others seeing their data??

Upvotes: 0

Views: 1910

Answers (3)

user13132197
user13132197

Reputation:

You could set up a relationship inside the User.php model.

public function servicios() {
   return $this->hasMany(Servicio::class);
}

Then in your controller:

public function index()
{
    $servicios = auth()->user()->servicios;

    return view('home', compact('servicios'));
}

Upvotes: 1

OMR
OMR

Reputation: 12188

you should get the user from your request, then filter by its id ...

  public function index()
{
$user_id=app('request')->user()->id;
    $servicios = App\Servicio::where('user_id',$user_id)->all();
    return view('home', compact('servicios'));
}

the user will be present in your request, to make sure of that you should but the route that use this method in (auth) middleware

Upvotes: 0

Ali
Ali

Reputation: 3666

You can get the user's list of services easily using Auth::user(), example:

User::with(['servicios'])->find(Auth::id());

Upvotes: 0

Related Questions