I'm kind of new using laravel.
I created delete function but it doesnt work as I wanted to. Here are the codes in view, controller as well as routes. Could you guys tell me what was wrong in the code? Thanks
View:
<div class="btn-group">
<a class="btn btn-info" href="{{ URL::to('/delete_data_tanah/{id}') }}">
<i class="fa fa-close"
onclick="return confirm('Are you sure you want to delete this data?');">----</i>
</a>
</div>
Controller:
public function delete($id){
\App\Tbl_object::where('id_objects', '=', $id)->delete();
return redirect('/list_tanah')->with('Success', 'Data telah dihapus');
}
Routes:
Route::post('/delete_data_tanah/{id}', 'formulir_tanah#delete');
Controller:
class formulir_tanah extends Controller
{
public function index()
{
$query_tanah = \App\Tbl_object::where('id_objects_referencies', '=', '1')->get();
$query_view = \App\Tbl_view::where('id_objects_referencies', '=', '1')->get();
$data = ['page_title' => 'Kertas Kerja Penilaian Tanah', 'query_tanah' => $query_tanah, 'query_view' => $query_view];
return view('admin/list_tanah')->with($data);
}
}
Try this:
in your blade.php, change {id} to {$data->id}
<div class="btn-group">
<a class="btn btn-info" href="{{ URL::to('/delete_data_tanah/{$data->id}') }}">
<i class="fa fa-close"
onclick="return confirm('Are you sure you want to delete this data?');">----</i>
</a>
then in your controller, add the id variable:
class formulir_tanah extends Controller { public function index(){
//ambil semua data dari table categories
$query_tanah = \App\Tbl_object::where('id_objects_referencies', '=', '1')->first();
$query_view = \App\Tbl_view::where('id_objects_referencies', '=', '1') ->first();
$data = ['id' => $query_view->id, 'page_title' => 'Kertas Kerja Penilaian Tanah', 'query_tanah' => $query_tanah, 'query_view' => $query_view ];
return view('admin/list_tanah')->with($data);
}
your code doesn't work since laravel doesn't know what row to delete since there is no specific id in your return.
Apply these changes to your code:
Route::delete('/delete_data_tanah/{id}', 'formulir_tanah#delete');
and in your view you need to wrap the button in a form
<form action="{{ URL::to('/delete_data_tanah/{id}') }}" method="post">
#method('DELETE')
#csrf
<button class="btn btn-danger" type="submit">Delete</button>
</form>
Related
View:
<td>
<div class="template-demo">
<button type="button" onclick="location.href=' {{ route ('SupAd.View_PL_Accnt/{$id}') }}'" class="btn btn-outline-info btn-icon-text">
<i class="ti-search btn-icon-append"></i>View
</button>
</td>
Route:
`Route::get('View_PL_Accnt', [SupAdController::class, 'View_PL_Accnt'])->name('SupAd.View_PL_Accnt/{$id}');`
Controller:
public function View_PL_Accnt(Request $request){
$id = $request->id;
$data = User::find($id);
return view('dashboards.SupAd.pages.index.View_PL_Accnt', compact (['data', 'id']));
}
View_PL_Accnt.blade.php :
<h3 class="SupAd_name">{{ data['name'] }}</h3>
Error:
Use of undefined constant data - assumed 'data' (this will throw an Error in a future version of PHP) (View: C:\Users\CuatrosMarias\Documents\GitHub\IPS\resources\views\dashboards\SupAd\pages\index\View_PL_Accnt.blade.php)
Error
You need to send variables using with() in your controller
return view('dashboards.SupAd.pages.index.View_PL_Accnt')->with('data',$data)->with('id',$id);
Your View Accnt.blade.php you have used data as constant you need to use it as variable
Eloquent result gives object so you can access the name property of your result object like below
{{ $data->name }}
typo error {{ $data['name'] }} $ is missing at the view
Try this one works fine in my side always..
->with(compact('data', 'id'));
View:
<button type="button" onclick="location.href=' {{ route ('SupAd.View_PL_Accnt', [$user->id]) }}'" class="btn btn-outline-info btn-icon-text">
<i class="ti-search btn-icon-append"></i>View
</button>
Route:
Route::get('View_PL_Accnt/{id}', [SupAdController::class, 'View_PL_Accnt'])->name('SupAd.View_PL_Accnt');
Controller:
public function View_PL_Accnt($id){
$data = User::find($id);
return view('dashboards.SupAd.pages.index.View_PL_Accnt', compact (['data', 'id']));
View_PL_Accnt.blade.php :
<h3 class="SupAd_name">{{ $data->name }}</h3>
I have a view that show some data and have edit feature, but when clicked edit button, user will be redirected to http://localhost:8000/posts/2/edit, I dont want post id appear in the URL, what should I do?
<table class="table table-bordered">
<tr>
<th width="20px" class="text-center">No</th>
<th>Title</th>
<th>Content</th>
<th width="280px" class="text-center">Action</th>
</tr>
#foreach ($posts as $post)
<tr>
<td class="text-center">{{ ++$i }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->content }}</td>
<td class="text-center">
<form action="{{ route('posts.destroy',$post->id) }}" method="POST">
<a class="btn btn-info btn-sm" href="{{ route('posts.show',$post->id) }}">Show</a>
<a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Delete?')">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
here is the controller
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
here is the route
Route::get('/', function () {
return view('welcome');
});
Route::resource('posts', App\Http\Controllers\PostController::class);
Auth::routes();
Thanks in advance
If you want to prevent users to edit posts that they did not create:
public function edit(Post $post)
{
if(Auth::user()->id != $post->user_id) {
throw new \Exception("Access denied", 403);
}
return view('posts.edit', compact('post'));
}
you need to use the Auth class offcourse:
use Illuminate\Support\Facades\Auth;
You need to do the same for the delete function
why you don't the id to appear in url. i can not see the reason to do that because there should be some unique key to edit the post. the only way i see is to add in the database a slug column and put it as unique. when adding a post put the title replacing space with '_' as a slug. make sure it is unique in validation. and in your edit and show code send the slug instead of the id.
route('posts.edit',$post->slug)
don't use dependency injection in controller
public function edit( $slug)
{
$post = Post::where('slug','=',$slug)->first();
return view('posts.edit', compact('post'));
}
hi
I think it will help you
your route will be like this:
Route::resource('posts', App\Http\Controllers\PostController::class)->except([
'edit'
]);
or
Route::resource('posts', App\Http\Controllers\PostController::class, ['only' => ['index', 'destroy', 'update' , 'create' , 'store']]);
or even you can write each route separately...
and write your edit route, separate :
Route::post('/post/edit', [App\Http\Controllers\PostController::class, "edit"])->name('post.edit');
delete #method('DELETE') from your blade and add this input to your blade :
<input type="hidden" name="post_id" value="{{$post->id}}" />
and change this :
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
to this :
public function edit(Request $request)
{
$post_id = $request->post_id;
//write your code here
return view('posts.edit', compact('post'));
}
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 am using Laravel Framework version 5.2.45.
I have created a simple view that outputs my todos:
#foreach($todos as $todo)
{{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>
<hr>
#endforeach
Within my routes I have created the following route to delete a todo:
Route::get('/todo/delete/{id}', [
'uses' => 'TodosController#delete',
'as' => 'todo.delete'
]);
Within my TodosController I created the following delete method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Todo;
class TodosController extends Controller
{
public function delete($id) {
$todo = Todo::find($id);
$todo->delete();
return redirect()->back();
}
// ...
When I press the button in the frontend nothing happens. I do not get any error...
Any suggestions what is wrong with my implementation?
Appreciate your replies!
You are using button not tag
turn your code from
#foreach($todos as $todo)
{{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>
<hr>
#endforeach
to
#foreach($todos as $todo)
{{ $todo->todo }} x
<hr>
#endforeach
Try Below code, You have used a button instead of a tag
#foreach($todos as $todo)
{{ $todo->todo }} x
<hr>
#endforeach
You should do like this :
Delete Button :
<a class="btn btn-primary" href="{{ route('todo.delete',$todo->id) }}">Delete</a>
And delete function look like below :
public function delete($id) {
try {
$delete_flag = Todo::where(['id' => $id])->first();
$delete_flag->delete();
return redirect()->back()->with('success', 'Todo deleted successfully');
} catch (Exception $ex) {
return redirect()->back()->with('error', 'Something went wrong');
}
}
#foreach($todos as $todo)
{{ $todo->todo }} x
#endforeach
delete code--
$toDo = Todo::findOrFail($id)->delete();
if($toDo){
return response()->josn(['message'=>'deleted']);
}
I am using this delete button to delete task in table
<button class="btn btn-danger delete pull-right"
data-action="/projects/{{ $project->id }}/tasks/{{ $task->id }}"
data-token="{{csrf_token()}}">
<i class="fa fa-trash-o"></i>Delete
</button>
this is delete controller
public function deleteOneProjectTask($projectId, $taskId)
{
DB::table('tasks')
->where('project_id', $projectId)
->where('id', $taskId)
->delete();
return redirect()->route('projects.show')->with('info', 'Task deleted successfully');
}
and routes
Route::delete('projects/{projects}/tasks/{tasks}', [
'uses' => '\App\Http\Controllers\ProjectTasksController#deleteOneProjectTask',
]);
but when I click delete button it is not delete task. but when I refresh it it will delete. how can fix this?