I'm using the friendship package by hootlex but I'm not quite sure how I get the user information (username etc.) when I'm getting all friend requests and displaying them in a foreach loop.
Basically what I have done is this, to return the view:
/**
* #return mixed
*
* View friend requests
*/
public function getFriendRequests() {
$user = Auth::user();
return view('friends.requests')
-> with([
'profile' => $user -> profile,
'user' => $user,
'received_requests' => $user -> getFriendRequests(),
'sent_requests' => $user -> getPendingFriendships()
]);
}
And then in my view:
<div class="block block-green">
<div class="block-head">
<h4><i class="fa fa-fw fa-exclamation-circle"></i>Venneforespørsler ({{ count($received_requests) }})</h4>
</div>
<div class="block-body">
#foreach ($received_requests as $rr)
<div class="request">
<div class="thumb">{{-- PROFILE THUMB HERE --}}</div>
<div class="username">{{-- SENDERS USERNAME HERE --}}</div>
<div class="actions">
<form method="post" action="/friends/request/accept/{{ $rr -> id }}">
<button type="submit" class="btn btn-success"><i class="fa fa-fw fa-check"></i>Aksepter</button>
</form>
<form method="post" action="/friends/request/deny/{{ $rr -> id }}">
<button type="submit" class="btn btn-danger"><i class="fa fa-fw fa-times"></i>Avslå</button>
</form>
</div>
</div>
#endforeach
</div>
</div>
So basically what I'm wondering, how would I get the username / other information from the User model on each friend request?
Thanks in advance.
Your $rr variable contains an object of class Hootlex\Friendships\Models\Friendship - you can see its source code here: https://github.com/hootlex/laravel-friendships/blob/master/src/Models/Friendship.php.
As you can see, this model allows you to access both sender and recipient of given friend request via properties of the same name.
Therefore, in order to get username of the sender, you'll need to access it with:
$rr->sender->username
Related
I've made a blog and now I'm trying to implement a comment section. I want it so that when the user tries to post, it's saves the comment and redirects the user to the same page. But when I write a comment and try to post it, the application redirects me to a different page. I'm learning how to make a blog with laravel, so I don't know when to use url and when to use routes. Here's the code that I've written.
#auth
<div class="card ml-5 col-lg-8">
<ul class="list-group list-group-horizontal">
<h5 class="list-group-item active">
Comments
<h5>
<div class="card-body">
<form method="post" action="{{url('save-comment/'.Str::slug($blog->title).'/'.$blog->id)}}">
#csrf
<textarea name="comment" class="form-control py-5"></textarea>
<input type="submit" class="btn btn-primary mt-3">
</div>
</ul>
</div>
#endauth
<div class="card ml-5 col-lg-8">
<h5 class="card-header mb-4">Comments<span class="badge badge-info ml-2"> {{count($blog->comments)}}</span></h5>
<div class="card-body mt-3">
#if($blog->comments)
#foreach($blog->comments as $comment)
<blockquote class="blockquote">
<p class="mb-0">{{$comment->comment}}</p>
<footer class="blockquote-footer">Username</footer>
</blockquote>
<hr>
#endforeach
#endif
</div>
</div>
BlogController :
function save_comment(Request $request,$slug,$id)
{
$request->validate([
'comment'=>'required',
]);
$data = new Comment;
$data->user_id=$request->user()->id;
$data->post_id=$id;
$data->comment=$request->comment;
$data->save();
return back();
}
Routes :
Route::get('/blog/', [App\Http\Controllers\BlogController::class, 'index'])->name('blog');
Route::get('blogs/{slug}','App\Http\Controllers\BlogController#getArticles')->name('article.show');
Route::get('blog.update/{id}','App\Http\Controllers\BlogController#edit');
Route::put('blog.update/{id}','App\Http\Controllers\BlogController#update');
Route::post('save_comment/{slug}/{id}','App\Http\Controllers\BlogController#save_comment')->name('save_comment');
Route::get('/admin/blog', 'App\Http\Controllers\BlogController#getBlog')->name('admin.blog');
If there's someone willing to assist come up with a solution to this problem, please assist me. I think the problem lies where I've written the url lies. When I change the url to route, it gives me an error of route not defined.
Route::resource('/blog','App\Http\Controllers\BlogController');
It redirects you to an empty page because you made a mistake on the url of your route. In your web.php file, your route is :
Route::post('save_comment/{slug}/{id}', 'App\Http\Controllers\BlogController#save_comment')->name('save_comment');
While in your form you wrote save-comment/ :
<form method="post" action="{{url('save-comment/'.Str::slug($blog->title).'/'. $blog->id)}}">
The error is due to this. I therefore advise you to modify the action in your form like this save_comment/:
<form method="post" action="{{url('save_comment/'.Str::slug($blog->title).'/'. $blog->id)}}">
This should be fixed !
Please change your code like this and check...
action="{{route('save_comment', $blog->id])}}"
Route::post('save_comment/{id}','App\Http\Controllers\BlogController#save_comment')->name('save_comment');
**BlogController**
function save_comment($id, Request $request)
{
$request->validate([
'comment'=>'required',
]);
$data = new Comment;
$data->user_id=$request->user()->id;
$data->post_id=$id;
$data->comment=$request->comment;
$data->save();
return back();
}
I am very new to laravel and I am really terrible with routing. I want to delete the specific data but it say that route is undefined
CandidateController.php
this is my method to delete
public function destroy(Form $candidates)
{
$candidates->delete();
return redirect()->route('candidate.approve');
}
route
Route::resource('candidates', CandidateController::class);
I am using a resourse, when I go through the tutorial, it shortened my code into above. When I clicked the button delete, it says that Undefined route [candidate.approve]. Can someone help me where I went wrong?
blade
#foreach ($candidates as $candidate)
<div class="modal__content">
<div class="p-5 text-center"> <i data-feather="x-circle" class="w-16 h-16 text-theme-6 mx-auto mt-3"></i>
<form action="{{ route('candidates.destroy', $candidate->id) }}" method="POST">
#csrf
#method('DELETE')
<div class="text-3xl mt-5">Are you sure?</div>
<div class="text-gray-600 mt-2">Do you really want to delete these records? This process cannot be undone.</div>
<button type="button" data-dismiss="modal" class="button w-24 border text-gray-700 dark:border-dark-5 dark:text-gray-300 mr-1">Cancel</button>
<button type="submit" title="delete" class="button w-24 bg-theme-6 text-white" >Delete</button>
</div>
<div class="px-5 pb-8 text-center">
</div>
</div>
</form>
</div>
#endforeach
web.php
Route::get('application/approve/{id}', 'CandidateController#postApprove')->name('application');
Route::get('candidate', [CandidateController::class, 'approve'])->name('candidate.approve');
Route::resource('candidates', CandidateController::class);
Just add new Route with candidate.approve name before Route::resource.
your web.php file will be like this
Route::get('your-url', [CandidateController::class, 'approve')->name('candidate.approve');
Route::resource('candidates', CandidateController::class);
But its better to use prural for named route, like the resource controller :
candidates.create
candidates.store
...
UPDATE
Since i know the flow of the app, you should use this on controller:
return back();
Why? because when admin click Delete on modal, it will goes to another URL to delete data from DB. After delete, return back() will redirect admin to previous URL
I'm making a "teacher's" app, and I want to make a log-in page which changes depending if there's registered users in the database or not.
I want to make a redirection button to a create user page if there aren't auth users in database, and to make a select user view if the database have one or more users.
The problem is that I don't know how to exactly do this, 'cause the view always shows me the first statement (what I've got in the if), also if in the database are registered users. Can anyone help me with this please?
This is the blade file:
#if (empty(Auth::user()->id))
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
Here you have the controller index method:
public function index()
{
$users = User::all();
return view('/', compact('users'));
}
And finally here you have the page:
The following code is the sample for it, kindly replace code accordingly
#if(!$user)
//show button
#else
//dont show button
#endif
I think your question is you want to check if there is user in database.
So no need to check if the user authenticated but to check if there is user on the database.
In your controller
public function index() {
return view('/', ['users' => User::all()]);
}
and in your blade file
#if(!$users)
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
This function will get the current authenticated user: Auth::user(). I guess what you are trying to achieve is #if(empty($users)) where $users is the variable you are passing on controller.
If you want to verify if the user that accessed to that view is authenticated you can simply use #auth and #guest.
Also i would suggest you to change your button to an <a> tag and your href would be <a href="{{ route('route.name') }}" where route.name would be defined in your routes file.
in your controller:
you can create a folder inside views called users and then the index.blade.php (views/users/index.blade.php)
public function index()
{
$users = Users::all();
return view('users.index')->with('users', $users);
}
in your view:
#if(count($users) < 1)
...
#else
...
#endif
count is validating if the $users array length is less then 1 (in other words if the array is empty).
Alternative you can you isEmpty()
#if($users->isEmpty())
...
#else
...
#endif
I have 2 questions and I need your help.First of all, I have made a delete route for comments, but other users logged can also delete comments from direct link...link.com/deleteComment/id. How to make this available only for owner of the comment?The owner id is saved in database and can be accessed with {{ $comment->user_id }}.
Second problem...In my view, when I click on a photo which have no comments, I'm receiving undefined variable comment, but I dont know why because on photos with comments, I have no problem with that.Can I make something like if comments != empty, dont show it or something like that?
CommentsController:
public function store(Request $request, $post_id)
{
$this->validate($request, array(
'comment' => 'required|min:5|max:2000',
));
$post = Post::find($post_id);
$comment = new Comment();
$comment->username = Auth::user()->username;
$comment->email = Auth::user()->email;
$comment->user_id = Auth::user()->id;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->post()->associate($post);
$comment->save();
Session::flash('message', "Message posted successfully!");
return Redirect::back();
}
PostsController:
public function delete($id){
DB::table('posts')->where('id',$id)->delete();
return redirect('/profile/' . auth()->user()->id);
}
My view
#foreach($post->comments as $comment)
<div class="comment d-flex ">
<p><strong><a class="text-dark" href="/profile/{{ $comment->user_id }}">{{ $comment->username}}</a>: </strong> {{ $comment->comment}}</p>
#can('update', $post->user->profile)
<div class="dropdown col-md-6">
<button type="button" class="btn btn-primary dropdown-toggle btn-sm" style="background-color: #ffffff00;border: 1px solid #555;color: black;padding: 0 5px" data-toggle="dropdown">
Select
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Edit comment</a>
<a class="dropdown-item" title="Options" style="text-decoration: none;" href="/deleteComment/{{$comment->id}}">Delete comment</a>
</div>
</div>
</div>
#endcan
#endforeach
My route
Route::post('comments/{post_id}', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
Route::get('/deleteComment/{id}', 'CommentsController#delete');
Try this to restrict the deletion only for the authenticated user who owns the comment:
/**
* Comments Controller Method Delete
*/
public function delete($id){
if(!DB::table('comments')->where('id',$id)->where('user_id',auth()->user()->id)->delete()){
Session::flash('remove', "You do not have permission to delete the comment!");
}else{
Session::flash('remove', "Message removed successfully!");
}
return Redirect::back();
}
For your second question, I think that what happens is that by not having comments you are using the variable without results.
You can try to enclose the statement where you use the variable $comments using this.
For Controller or others files php
if (!$comment->isEmpty()) {
//your code
}
if ($comment->count()) {
//your code
}
if (count($comment)) {
//your code
}
For Blade
#if(!$comment->isEmpty())
//your code
#endif
#if($comment->count())
//your code
#endif
#if(count($comment))
//your code
#endif
I hope I could help you, if not, please attach more code where they appear exactly what he says, since comments and delete the picture, since I have not seen in the code you have attached. Thanks and good luck.
References
$comment->isEmpty
$comment->count() and count($comment)
Updated
<div class="row">
<div class="col-md-12">
#if(!$post->comments->isEmpty()) //****Added
#if($post->comments->count() > 0)
#foreach($post->comments as $comment)
<div class="comment d-flex ">
<p><strong><a class="text-dark"
href="/profile/{{ $comment->user_id }}">{{ $comment->username}}</a>:
</strong> {{ isset($comment->comment) ? $comment->comment : "--" }}</p>
#can('update', $post->user->profile)
<div class="dropdown col-md-6">
<button type="button" class="btn btn-primary dropdown-toggle btn-sm"
style="background-color: #ffffff00;border: 1px solid #555;color: black;padding: 0 5px"
data-toggle="dropdown">
Select
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Edit comment</a>
<a class="dropdown-item" title="Options" style="text-decoration: none;"
href="/deleteComment/{{$comment->id}}">Delete comment</a>
</div>
</div>
</div>
#endcan
#endforeach
#endif
#endif //****Added
</div>
</div>
Updated for delete if admin or no
/**
* Comments Controller Method Delete
*/
public function delete($id)
{
$comment = DB::table('comments')->where('id', $id):
if(!auth()->user()->admin){
$comment->where('user_id', auth()->user()->id);
}
if (!$comment->delete()) {
Session::flash('remove', "You do not have permission to delete the comment!");
} else {
Session::flash('remove', "Message removed successfully!");
}
return Redirect::back();
}
The first question can be done easily. In your destroy() function, just check comment owner:
// Check comment owner
if($comment->user_id != \Auth::id()){
return abort(401);
}
// Do logic code to delete comment.
The second question, you can check exist comment like this :
if(! $comments->isEmpty()) {
// Do logic code to show comment
}
I would like to ask if it is possible to validate a href element in laravel.
For example, I'm having a bunch of people responses in my guest book and each user is able do delete his posts. I'm deleting it like this:
<div class="col-lg-2">
<ul class="list-unstyled trash">
<li>
<a href="/responses/{{$response->id}}">
<span onclick="alertDialog()" class="glyphicon glyphicon-trash"></span></a></li>
<li><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#{{$response->id}}">Edit</button></li>
</ul>
</div>
Unfortunately, every single user can change "/responses/{{$response->id}}"> id via browser developer tools and delete other user's responses. Is there any possible solutions to prevent this issue?
Just check the logged user before rendering that html section:
<div class="col-lg-2">
<!-- assuming post is your variable and user is a property which references the user who created the record -->
#if($post->user == Auth::id())
<ul class="list-unstyled trash">
<li>
<a href="/responses/{{$response->id}}">
<span onclick="alertDialog()" class="glyphicon glyphicon-trash"></span></a></li>
<li><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#{{$response->id}}">Edit</button></li>
</ul>
#endif
</div>
This way only the user who owns the post will be able to see the button in the html.
You need to use policies to check if the user that tries to delete a record is its owner:
public function delete(User $user, Model $model)
{
return $user->id === $model->user_id;
}
Or you can do it manually in a controller method:
if (auth()->id() === $model->user_id) {
// Delete the record
}
You should make /responses/{{$response->id}} a POST route and verify that the passed id matches with the authenticated users id. ( Auth::user()->id;)
I ended up checking like this in my destroy(id) method:
$count = Comment::where(['response_id' => $id])->count();
if (($responses->where('id',$id)->value('guests_email') == Cookie::get('email') && ($count==0)) || (Auth::check()))