Latest

Monday, July 10, 2017

laravel url /delete/id will delete a comment, need it to be disabled

Asked by: kevinS


I can delete comments when i type this in the url.. /delete/{id} from the comment. I need that to be private/disabled.

Route:

Route::get('/delete/{id}', 'commentController@delete');

controller:

function delete($id)
{
    comment::where('id',$id)->delete();
    return back();
}

view:

<a href="/delete/{{ $comment->id}}">
    <button type="submit" class="btn btn-danger pull-right">Delete</button>
</a>

Answers

Answered by: Mohammad b at 2017-07-10 05:41PM Accepted



I think you want to show delete comment links only for comment owner

so in your view you should have if condition

for example:

@if (Auth::user() && (Auth::user()->id == $comment->user_id))
    <a href="/delete/{{ $comment->id}}">   <button type="submit" class="btn btn-danger pull-right">Delete</button></a>
@endif

in this condition comment delete link only display for comment owner $comment->user_id is comment owner id that i dont know how you store it in your database

of course you should check it in you controller too like this:

{
if (Auth::user() && (Auth::user()->id == $comment->user_id)) {
    comment::where('id',$id)->delete();
    return back();
}else
return 'you dont have permission';
}

and if you want to limit it only for admin , in condition you should check user is admin like this:

Auth::user()->id == [admin_id]

OR define a admin role and check

Auth::user()->role == 'admin'

Don't remember to study form-method-spoofing to choose best way to delete data in your database



Answered by: user2963176 at 2017-07-10 05:49PM



You can implement a middleware for admin users and then in your controller construtor you only need to do something like:

public function __construct()
{
    $this->middleware('admin')->only('delete');
}

You can read more about middleware here



Answered by: Martin Bean at 2017-07-10 05:53PM



You should not be able to delete anything in your application using a GET request, i.e. by visiting a URL. What happens if Google finds these links a crawls them? It’s then going to initiate delete requests, and your users are going to be angry.

Instead, items should be deleted by making a DELETE request (or a POST request with a hidden _method parameter with the value of DELETE), and then also protected by authentication, and optional authorisation (to determine which users can delete the given resource).

If you use Laravel’s resource controllers, it will set this route up for you. Running php artisan make:controller CommentController --resource --model=Comment will create a controller with actions for your Comment model, such as creating, editing, and deleting. You then want to apply the auth middleware to at least your destroy() action, and if only specific users should be able to delete specific comments, then you need to look at authorisation using policies.




Source

No comments:

Post a Comment

Adbox