Reputation: 21
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>
Upvotes: 1
Views: 1062
Reputation: 49
Route::get('/myEmails/{user}','PagesController@myEmailsShow')->name('myemails');
with the controller
use App\Email;
use App\User;
public function myEmailsShow(User $user)
{
///calling the model Email at parameters instead of $id eloquent automatically the data from DB
$myEmails = Email::where('user_id',$user->id)->get();
return view('content.myEmails')->with('myEmails', $myEmails);
}
The link has little modifications
@if(Auth::check())
<a class="nav-link text-white" href="{{route('myemails', $user->id)}}"> my emails</a>
@endif
displaying the value
@foreach($myEmails as $myEmail)
{{$myEmail->name}}
@endforeach
Upvotes: 0
Reputation: 148
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('App\Models\Email');
}
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.
Upvotes: 2