Skip to content
Advertisement

How can I show items belonging to a logged in user in Laravel?

I want to show the emails that the logged in user has sent from the database

This is the route code:

Route::get('/myEmails/{id}','PagesController@myEmailsShow');

This is the function in the controller:

public function myEmailsShow($id)
{   
  $myEmails = DB::table('emails')->where('user_id',$id)->get();
  return view('content.myEmails', compact('myEmails'));
}

This is the a link where the user click to open the page:

@if(Auth::check())
  <a class="nav-link text-white" href="/myEmails/{id}"> my emails</a>
@endif

And here where i want to show the data (i am showing only the name for test):

<div class="row">
  @foreach($myEmails as $myEmail)
    {{$myEmail->name}}
  @endforeach
</div>

Advertisement

Answer

I think the best way to accomplish your goals here would be using a hasMany relationship between User and Emails (if emails is a Model).

//User.php

public function emails()
{
    return $this->hasMany('AppModelsEmail');
}

In the controller, apply the Auth middleware to the myEmailsShow method in a constructor:

//PagesController.php

public function __construct()
{
  $this->middleware('auth')->only(['myEmailsShow']);
}

Then, in your myEmailsShow method, do something like the following:

//PagesController.php

public function myEmailsShow()
{
    // Middleware Eliminates the need for ID in the function.
    $user = auth()->user();
    $myEmails = $user->emails;
    return view('content.myEmails', compact('myEmails'));
}

You can remove the ID parameter from the route and just make it something like Route::get('/myEmails', 'PagesController@myEmailsShow');. Only users who are logged in will be able to access this page, and they will only see emails belonging to them.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement