Reputation: 135
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.
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
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
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
Reputation: 3666
You can get the user's list of services easily using Auth::user()
, example:
User::with(['servicios'])->find(Auth::id());
Upvotes: 0