Delete method in laravel receives id parameter in null - laravel

When I want to delete a comment from a photo, the id is sent by parameter but the delete () function that deletes that record receives the same $ id as null.
First my route
Route::get('/comment/delete/{id}', [App\Http\Controllers\CommentController::class, 'delete'])->name('comment.delete');
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comments';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function images()
{
return $this->belongsTo(Image::class, 'image_id');
}
}
CommentController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function save(Request $request){
//Validacion
$validate = $this->validate($request, [
'image_id' => 'required|integer',
'content' => 'string|required'
]);
//Recoger datos
$user = \Auth::user();
$content = $request->input('content');
$image_id = $request->input('image_id');
//Asigno los valores a mi objeto
$comment = new Comment;
$comment->user_id = $user->id;
$comment->image_id = $image_id;
$comment->content = $content;
//guardar en la base de datos
$comment->save();
return redirect()->route('image.detail', [
'id' => $image_id
])->with([
'message' => 'Haz hecho un comentario'
]);
}
public function delete($id){
//Conseguir datos del usuario identificado
$user = \Auth::user();
//Conseguir objeto del comentario
$comment = Comment::find($id);
dd($comment);
//Comprobar si soy el dueño del comentario o de la publicacion
if ($user && ($comment->users_id == $user->id || $comment->images_id->users_id == $user->id)) {
$comment->delete();
return redirect()->route('image.detail', ['id' => $comment->images->id])
->with([
'message' => 'Comentario eliminado'
]);
}else{
return redirect()->route('image.detail', ['id' => $comment->images->id])
->with([
'message' => 'Comentario NO eliminado!'
]);
}
}
}
View:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
#include('includes.message')
<div class="card pub_image pub_image_detail">
<div class="card-header">
#if($image->user->image)
<div class="container-avatar">
<img src="{{route('user.avatar', ['filename' => $image->user->image])}}" class="avatar">
</div>
#endif
<div class="data-user">
{{$image->user->name.' '.$image->user->surname}}
<span class="nickname">
{{' | #'.$image->user->nick}}
</span>
</div>
</div>
<div class="card-body">
<div class="image-container">
<img src="{{ route('image.file', ['filename' => $image->imagen_path]) }}" alt=""/>
</div>
<div class="description">
<span class="nickname">{{'#'.$image->user->nick}}</span>
<span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($image->created_at)}}</span>
<p>{{$image->description}}</p>
</div>
<div class="likes">
<img src="{{asset('/img/corazon-negro.png')}}" alt=""/>
</div>
<div class="clearfix"></div>
<div class="comments">
<h4>Comentarios ({{count($image->comments)}})</h4>
<hr>
<form action="{{route('comment.save')}}" method="POST">
#csrf
<input type="hidden" name="image_id" value="{{$image->id}}">
<p>
<textarea name="content" id="" cols="30" rows="10" class="form-control box-comment {{$errors->has('content') ? 'is-invalid' : ''}}"></textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</p>
<button type="submit" class="btn btn-success">
Enviar
</button>
</form>
#foreach($image->comments as $comment)
<div class="comment">
<span class="nickname">{{'#'.$comment->user->nick}}</span>
<span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($comment->created_at)}}</span>
<p>{{$comment->content}}</p>
#if(Auth::check() && ($comment->user->id == Auth::user()->id || $comment->images->users_id == Auth::user()->id))
<a href="{{route('comment.delete', ['id', $comment->id])}}" class="btn btn-sm btn-danger">
Eliminar
</a>
#endif
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
I would like to know how I can make the delete button correctly send the id by parameter to the controller, that it receives it and then removes the comment.
Thanks!

Your issue is not defining the id correctly in the array :
{{ route('comment.delete', ['id', $comment->id]) }}
It should be like this:
{{ route('comment.delete', ['id' => $comment->id]) }}

Related

Eloquent relationship through 2 models

I have Post model:
class Post extends Model
{
use HasFactory;
protected $fillable = [
'category_id',
'user_id',
'img',
'title',
'content',
];
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
public function comments(){
return $this->hasMany(Comment::class)->where('parent_id', '0');
}
}
Comments model:
class Comment extends Model
{
use HasFactory;
protected $fillable = [
'post_id',
'user_id',
'parent_id',
'content',
// 'img'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function replies()
{
return $this->hasMany(Comment::class,'parent_id');
}
}
Can I use the replies function via the post model?
For example:
#foreach($comments->comments->replies->sortByDesc('id') as $comment)
#endforeach
I am just trying to add replies to comments.
<div class="col-md-12">
<div class="blog-comment">
<hr/>
<ul class="comments">
<li class="clearfix">
#foreach($post as $comments)
#foreach($comments->comments->sortByDesc('id') as $comment)
<img src="https://bootdey.com/img/Content/user_1.jpg" class="avatar">
<div class="post-comments">
<p class="meta d-flex justify-content-between">{{ $comments->user->name }}<span>{{ $comments->user->created_at }}</span></p>
<p>
{{ $comment->content }}
</p>
</div>
<form action="{{ route('comment.store') }}" method="POST" class="w-100">
#csrf
<div class="replyform d-flex mb-3">
<input type="hidden" name="post_id" value="{{ $comments->id }}">
<input type="hidden" name="parent_id" value="{{ $comment->id }}">
<input class="d-block ml-auto w-50 align-top" type="text" name="content" required>
<button type="submit" class="offset replysub fas fa-paper-plane ml-1"></button>
</div>
</form>
#endforeach
#endforeach
#foreach($comments->comments->replies->sortByDesc('id') as $comment)
#if($comment->parent_id !== 0)
<ul class="comments">
<li class="clearfix">
<img src="https://bootdey.com/img/Content/user_3.jpg" class="avatar">
<div class="post-comments">
<p class="meta">Dec 20, 2014 JohnDoe says : <i class="pull-right"><small>Reply</small></i></p>
<p>
{{ $comment->content }}
</p>
</div>
<input class="replyform d-block ml-auto mb-3 w-50" type="text" name="" value="">
</li>
</ul>
#endif
#endforeach
</li>
</ul>
</div>
</div>
Of course, I can take and pass one more variable to the template, but I heard that you shouldn't do this, it overloads the controller. Therefore, I try to do it through an eloquent relationship.
P.S. Or is there a way to do it in the post model? Like:
public function replies(){
return $this->hasMany(Comment::class)->where('parent_id', 'id(of parent comment)');
}

How to fix this error in Laravel when creating a category

I am creating a website for a blog. I have added a category page quickly updated, but not returned to the index: category.php,CategoriesController.php. I'm using Laravel v5.5 and OpenServer.
Category.php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['title', 'slug',];
public function user()
{
return $this->belongsToMany(
User::class,
'id_idcat',
'gid',
'idcat'
);
}
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
CategoriesController.php
namespace App\Http\Controllers\Admin;
use App\Category;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use View;
class CategoriesController extends Controller
{
public function index()
{
$categories = Category::all();
return view('admin.categories.index', ['categories' => $categories]);
}
public function create()
{
return view('admin.categories.create');
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required' //обязательно
]);
Category::create($request->all());
return redirect()->route('admin.categories.index');
}
}
create.blade.php
{!! Form::open(['route' => 'categories.store']) !!}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" name="cat">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}
I can not find a mistake. I did similar tasks several times.
Your Data isn't validating as there is no input named title because it's named cat, so your validator is redirecting you back with errors, but your blade isn't showing errors so you don't see them.
Change Name of the field in your create view and add errors as below:
Edit: also add CSRF to form
create.blade.php
#if ($errors->any())
<div class="alert alert-danger" role="alert">
#foreach ($errors->all() as $input_error)
{{ $input_error }}
#endforeach
</div>
#endif
{!! Form::open(['route' => 'categories.store']) !!}
{{ csrf_field() }}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" placeholder="" name="title">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}

"Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)"

When I am editing my post then I am prompted with the following error message
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'content' => 'required',
'category_id' => 'required'
]);
$post = Post::find($id);
if($request->hasFile('featured'))
{
$featured = $request->featured;
$featured_new_name = time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post->featured = 'uploads/posts/'.$featured_new_name;
}
$post->title = $request->title;
$post->content = $request->content;
$post->category_id = $request->category_id;
$post->save();
Session::flash('success', 'Post updated successfully.');
return redirect()->route('posts');
}
and blade code
<div class="form-group">
Select a Category
#foreach($categories as $category)
id}}"
#if($post->$category->id == $category->name)
selected
#endif
{{$category->name}}
#endforeach
List item
My Post method for post and category
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; // here set table's name
protected $primaryKey = 'id'; // here set table's primary Key field name
protected $fillable = ['id']; // here set all table's fields name
public function posts()
{
return $this->hasMany('App\Post');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App/Category');
}
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable=['title','content','category_id','featured','slug'];
}
}
Edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header bg-info">
<div class="text-center">
<h4 class="m-b-0 text-white">
<div class="panel panel-default">
<div class="panel-heading">
Edit Post:{{$post->title}}
</div>
<div class="panel-body">
<form action="{{route('post.update', ['id'=>$post->id])}} " method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for ="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for ="featured">Featured image</label> <input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for ="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit"> Update Post</button>
</div>
</div>
</form>
</div>
</div>
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Row -->
#stop
Controller...
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|mimes:jpeg,pdf,docx,png:5000',
'file'=>'required|mimes:jpeg,pdf,docx,png:5000',
'content'=>'required',
'category_id'=>'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file_name=time().$file->getClientOriginalName();
$file->move('uploads/posts', $file_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/posts'. $file_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
This the area in your blade where you are getting the issue:
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
Where are you fetching and providing $categories to this blade template? I mean the controller method which loads the edit blade?
Can you post that code as well?
And please update your question instead of posting answers.

Cant Display my Reply under the Comment Laravel 5.7

I can't display my reply under each comment. Here is my code...
Comment model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'user_id', 'topic', 'body', 'category',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Comment controller
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CommentController extends Controller
{
public function store(Request $request, $post)
{
$comment = new Comment;
$comment->body = $request->body;
$comment->user_id = Auth::user()->id;
$post = Post::find($post);
$post->comments()->save($comment);
return back();
}
public function replyStore(Request $request, $comment)
{
$comment = new Comment;
$comment->body = $request->body;
$comment->user_id = Auth::user()->id;
$comment = Comment::find($comment);
$comment->comments()->save($comment);
return back();
}
}
Routes
Route::post('/comment/store/{post}', 'CommentController#store')->name('comment.add');
Route::post('/reply/store/{commentid}', 'CommentController#replyStore')->name('reply.add');
View
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card">
<div class="card-header">{{$post->topic}}
Create New Post
</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<h3>{{$post->topic}}</h3>
<p>{{$post->body}}</p>
</div>
</div>
<form action="/comment/store/{{$post->id}}" method="post" class="mt-3">
#csrf
<div class="form-group">
<label for="">Comment :</label>
<textarea class="form-control" name="body" id="" rows="3"></textarea>
<br>
<input type="submit" value="Comment" class="btn btn-secondary">
</div>
</form>
<div class="row mt-5">
<div class="col-md-10 mx-auto">
<h6 style="border-bottom:1px solid #ccc;">Recent Comments</h6>
#foreach($post->comments as $comment)
<div class="col-md-12 bg-white shadow mt-3" style="padding:10px; border-radius:5px;">
<h4>{{$comment->user->name}}</h4>
<p>{{$comment->body}}</p>
<button type="submit" class="btn btn-link" onclick="toggleReply({{$comment->id}})">
Reply
</button>
<div class="row">
<div class="col-md-11 ml-auto">
{{-- #forelse ($replies as $repl)
<p>{{$repl->body}}</p>
#empty
#endforelse --}}
</div>
</div>
</div>
<form action="/reply/store/{{$comment->id}}" method="post"
class="mt-3 reply-form-{{$comment->id}} reply d-none">
#csrf
<div class="form-group">
<textarea class="form-control" name="body" id="" rows="3"></textarea>
<br>
<input type="submit" value="Reply" class="btn btn-secondary">
</div>
</form>
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
#section('js')
<script>
function toggleReply(commentId) {
$('.reply-form-' + commentId).toggleClass('d-none');
}
</script>
#endsection
I have created the normal table with parent_id but I don't know how to display the replies for each comment. Please, anyone who can help me with this - I am stranded here and the error coming from the second controller function which is replystore() saying it doesn't recognize the comments() method. Please help me out to display the reply.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pk5.roles' doesn't exist

I am able to insert records to employee_roles through tinker but unable to insert them through code
Role.php
<?php
namespace App\Models\Admin\Employee;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $table = 'employee_roles';
public function permissions()
{
return $this->belongsToMany('App\Models\Admin\Employee\Permission', 'employee_permission_role', 'role_id', 'permission_id');
}
}
RoleController.php
<?php
namespace App\Http\Controllers\Admin\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Employee\Employee;
use App\Models\Admin\Employee\Role;
use App\Models\Admin\Employee\Permission;
class RoleController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function index()
{
$roles = Role::all();
return view('admins.employees.roles.role', compact('roles'));
}
public function create()
{
$permissions = Permission::all();
return view('admins.employees.roles.create',compact('permissions'));
}
public function store(Request $request)
{
//dd($request);
$this->validate($request, [
'name' => 'required|unique:roles'
]);
$role = new Role();
$role->name = $request['name'];
$role->save();
$role->permissions()->sync($request->permission);
return redirect(route('admin.employee.role.index'));
}
admins.employees.roles.create.blade.php
#extends('layouts.admin')
#section('title', 'Role - Create')
#section('left-menu')
#endsection
#section('right-menu')
#endsection
#section('content')
<h1>Add an Employee Role</h1>
<br><br>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('admin.employee.role.store') }}" method="post">
#csrf
<div class="form-group">
<label for="name">Role Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Role Name" value="{{ old('name') }}">
</div>
<div class="form-row">
<div class="col-md-4">
<label for="name"><b>Customer Permissions</b></label>
#foreach ($permissions as $permission)
#if ($permission->for == 'Customer')
<div class="checkbox">
<label><input type="checkbox" name="permission[]" value="{{ $permission->id }}">{{ $permission->name }}</label>
</div>
#endif
#endforeach
</div>
<div class="col-md-4">
<label for="name"><b>Despatch Permissions</b></label>
#foreach ($permissions as $permission)
#if ($permission->for == 'Despatch')
<div class="checkbox">
<label><input type="checkbox" name="permission[]" value="{{ $permission->id }}">{{ $permission->name }}</label>
</div>
#endif
#endforeach
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
Back
</div>
</form>
#endsection
#section('pagescript')
#stop
$this->validate($request, [
'name' => 'required|unique:roles'
]);
You should fix table name as employee_roles
Because you don't have table as roles you said that in your Role model you're using employee_roles table ( protected $table = 'employee_roles';)

Resources