I'm trying to create post page with comments; however, it's not working when I add the comment to a post because the system doesn't recognize the post id. What I'm I doing wrong that it doesn't know that the post_id is equal to $post_id
I'm getting the following error:
SQLSTATE[HY000]: General error: 1364 Field 'post_id' doesn't have a default value (SQL: insert into comments (body, updated_at, created_at) values (This is a test comment, 2017-08-15 19:51:47, 2017-08-15 19:51:47))
COMMENTS FORM
<div class="well">
<h4>Leave a Comment:</h4>
<form role="form" method="post" action="{{ $post->id }}/comments">
{{ csrf_field() }}
<div class="form-group">
<textarea name="body" class="form-control" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
ROUTE
Route::post('/posts/{post}/comments', 'CommentController#store');
CONTROLLER
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
COMMENT MODEL
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
POST MODEL
class Post extends Model
{
public function addComment($body)
{
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
post_id isn't in fillable array:
class Comment extends Model
{
protected $fillable = ['body', 'post_id']; //<---
...
}
I see, your controller function doen't know what post your talking about. You need to use the post id that is coming back from your form and locate the post then you can save the new comment like this
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
As shown in the Laravel Docs 5.4 Eloquent it will fill the id in for you.
Also if I remember correctly you do not need to add ['post_id'] to your array of fillable fields.
The SQL error can be resolved by using a "column modifier". (see below)
Schema::table('users', function (Blueprint $table) {
$table->string('email')->nullable();
});
Laravel Docs 5.4 Migrations
in your table in mysql make sure your post_id is auto increment or can be "null". This error is saying post_id has no value and cant be default.
From the look of your code post_id is your primary key but not set to auto increment
Related
I'm working with Laravel 8 to develop my project which is an Online Forum. And in this forum, basically users can answer to questions.
So at the Controller, I put this for posting answers:
public function PostAnswer($id)
{
$validate_data = Validator::make(request()->all(),[
'answer' => 'required',
])->validated();
$answer = Answer::create([
'answer' => $validate_data['answer'],
'user_id' => auth()->user()->id,
'question_id' => $id,
]);
return back();
}
Note that $id variable is the question id.
But now the problem is whenever I try to add an answer, I get this error:
Illuminate\Database\QueryException SQLSTATE[HY000]: General error:
1364 Field 'answer' doesn't have a default value
The form behind this goes here:
<form action="{{ route('questions.answers', $show->id) }}" method="POST">
#csrf
<textarea name="answer" id="answer" class="form-control" rows="7"></textarea
#error('answer')
<div class="text-red-500 mt-2 text-sm">
{{ $message }}
</div>
#enderror
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And here is also the Migration of answers table:
public function up()
{
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->text('answer');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('question_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
If you want to look at relations between Models, here it is:
Question.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
User.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
So what is going wrong here, how can I fix this issue?
I would really appreciate if you share your idea or suggestion on this...
Thanks in advance.
in your Answer Model, make sure you have $fillable property with correct properties:
class Answer extends Model
{
protected $fillable = ['answer','user_id','question_id'];
....
}
I want to delete a single row of data in my pivot table. I don't get any error but when try to click on the button. It did not redirect me to anywhere so the delete function is not performed.
In the picture above I want to delete the highlighted id for user_id = 3
My scenario is that the user suddenly can't make it to even_id = 6 so the user wants to delete/unjoined the event.
route
Route::get('/user/event/{event}', 'HomeController#destroy')->name('user.event.destroy');
blade
#foreach ($events as $event)
<tr>
<td>{{$loop->index +1 }}</td>
<td>{{$event->event_name}}</td>
<td>{{$event->event_date}}</td>
<td>
<form method="POST" action="{{ route('user.event.destroy',$event)}}">
#csrf
#method('DELETE')
<a class="btn btn-danger">Unjoined!</a>
</form>
</td>
</tr>
#endforeach
controller
public function storeEventUser(Request $request)
{
$user = User::find(Auth::user()->id);
//how I storing my pivot data (just to show if anyone asking)
$user->events()->syncWithoutDetaching([$request->event_id]);
}
public function destroy($event)
{
$event= Event::findOrFail($event_id);
$user->events()->detach($event);
return redirect()->back()->with('success','Deleted.');
}
Event model
public function users()
{
return $this->belongsToMany(User::class,'event_user','event_id','user_id');
}
user model
public function events()
{
return $this->belongsToMany(Event::class,'event_user','user_id','event_id');
}
I am adjusting your controller method to use Route Model Binding for simplicity:
public function destroy(Event $event)
{
Auth::user()->events()->detach($event);
// or from the other side of the relationship
// $event->users()->detach(Auth::user());
return redirect()->back()->with('success', 'Deleted.');
}
As stated in the comments you need to adjust your route to Route::delete if you want to use the DELETE HTTP method that your form is spoofing via the #method('DELETE') blade directive.
Side note:
Auth::user() returns a User instance so you don't need to query for it again, in your storeEventUser method:
$user = Auth::user();
I want a user to delete a product when he clicks unlike button but I'm getting an error 404 url not found, but I have the url.
If I put dd($product) before $like = Like::findOrFail($product);
it displays the id(4) but if I put dd($like), then it throws an error 404. How can I make this function work?.
Controller
public function destroy($product)
{
$like = Like::findOrFail($product);
dd($like);
$like->delete();
return 'done';
}
Blade
<a class="remove" href="{{ route('product.unlike', ['product' => $product->id]) }}" > Unlike </a>
Route
Route::get('product/{product}/unlike', ['as' => 'product.unlike', 'uses' => 'LikeController#destroy']);
Like.php
class Like extends Model
{
use SoftDeletes;
protected $table = 'likeables';
protected $fillable = [
'user_id',
'product_id',
'likeable_id',
'likeable_type',
];
public function products()
{
return $this->morphedByMany('App\Product', 'likeable');
}
delete request should be post request not get
web.php
Route::delete('product/{product}/unlike','LikeController#destroy')->name('product.unlike');
blade.php
<form action="{{ route('product.unlike',[$product->id]) }}" method="post">
#csrf
#method('DELETE')
<button type="submit" class="remove"> Unlike </button>
</form>
controller
use App\Product;
...
public function destroy(Product $product) {
$product->delete();
return 'done';
}
Hope this helps!
Detach the Products corresponding to the like.
public function destroy($product)
{
Like::where('product_id', $product)
->where('user_id', auth()->user()->id)
->delete();
return 'done';
}
findOrFail will throw an exception which will cause the 404 when it can't find a record. You are using SoftDeletes so the record can exist in the database but doesn't mean that it hasn't been 'soft deleted'. If it has been soft deleted the scope will make it act like it isn't there.
Check your record with id == 4 to see if it has a deleted_at column with a value. If it does, it was deleted (soft deleted). You will have to adjust your query to be able to retrieve soft deleted records.
Laravel 6.x Docs - Eloquent - Soft Deletes - Querying Soft Deleted Models
I am trying to store data into my database using VueJs and I keep receiving 500 error
here is my code:
export default {
props: ['post_id','user_id'],
data: function () {
return {
body:'',
user_name : '',
}
},
and the methods is here:
methods: {
loadComments() {
// axios.get("../api/comment").then(({ data })=>(this.comments - data.data)
axios.get("../api/comment").then((response) => (this.comments = response.data.data)
// response => this.comments = response.data
);
},
create() {
axios.post('../api/comment',{body:this.body});
},
and here is a part of my form:
<form #submit.prevent="create()" id="myForm" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed">
<div class="form-group m-form__group row">
<div class="col-lg-6">
<label>name</label>
<input type="text" placeholder="insert name" name="body" class="form-control m-input" v-model="body">
</div>
<div class="col-lg-6">
<label>email</label>
<input type="text" placeholder="email" name="title" class="form-control m-input">
</div>
</div>
and the route for api laravel:
Route::resource('comment','CommentController');
and finally here is what I get as log error in laravel :
[2019-03-25 07:07:08] local.ERROR: SQLSTATE[HY000]: General error: 1364 Field 'body' doesn't have a default value (SQL: insert into comments (updated_at, created_at) values (2019-03-25 07:07:08, 2019-03-25 07:07:08)) {"exception":"[object] (Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'body' doesn't have a default value (SQL: insert into comments (updated_at, created_at) values (2019-03-25 07:07:08, 2019-03-25 07:07:08)) at C:\wamp\www\jabama3\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664, PDOException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'body' doesn't have a default value at C:\wamp\www\jabama3\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458)
i know that my form is not sending data and laravel needs the data but i dont know which part i am doing wrong .
Edit here is my store method :
public function store(Request $request)
{
Comment::create($request->all());
return (['message' => 'succes']);
}
and here is my table structure :
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->longText('body');
$table->integer('user_id')->nullable();
$table->string('user_email')->nullable();
$table->string('user_name');
$table->integer('status')->default('0');
$table->integer('post_id');
$table->timestamps();
});
This is because your body is empty when you inserting data to your table.
The reason is you are using Create a method for inserting data.
And Create method needs protected $fillable = ['field1','field2',...] array which have your table fields in your model.
Add $fillable to your model.
You can follow this link for more information relating to Mass Assignment
You create file Comments.php Model, you can update file Comments.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comments extends Model
{
protected $fillable = [
'body',
'user_id',
'user_email',
'user_name',
'status',
'post_id',
'created_at',
'updated_at'
];
}
Example Laravel + Vuejs Send Mail
I want to change the status of a task to complete. I have a status_id column in the database and 1 equals complete. I would like the click of the button to change the status_id to 1
My route
Route::patch('/tasks/completed/{Task}', 'TasksController#completedUpdate')->name('completedUpdate');
My button
<form action="{{ route('completedUpdate', $task->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<button type="submit" class="button is-inverted" style="margin-top: 10px;">Mark Complete</button>
</form>
My controller
public function completedUpdate(Request $request, $task)
{
$task->status_id = $request->status_id;
$task->save;
return redirect()->back()->with('message', 'task marked complete');
}
the error it gives me is:
Attempt to assign property of non-object
Let me know if any more info is needed
You should change:
public function completedUpdate(Request $request, $task)
{
$task->status_id = $request->status_id;
$task->save;
return redirect()->back()->with('message', 'task marked complete');
}
into:
public function completedUpdate(Request $request, Task $task)
{
$task->status_id = $request->status_id;
$task->save();
return redirect()->back()->with('message', 'task marked complete');
}
so you need to typehint type of $task variable and use save() method instead of save property.
Also probably instead of:
/tasks/completed/{Task}
you should use:
/tasks/completed/{task}
$task->save; should be $task->save();
With ->save, it is looking for a property on the model, hence the error message re 'assigning a property'. Whereas ->save() calls the save method on the object.
In your controller, you're assigning the $task->status_id a value of $request->status_id but you're actually not passing the status_id in your form in your HTML code. You can put a hidden element in your form which is <input name="status_id" value="1" />.
In the meanwhile, do not forget that $task->save; must be $task->save();
Good luck!