getting 500 error on laravel and vuejs inserting to database + logfile - php

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

Related

Laravel Livewire accessing json attribute fails with type error

I have a model with some typical columns and one json column. The Json is casted as array:
Model:
protected $casts = [
'client' => 'array'
];
In my Livewire component, I created the following validation rule
Livewire component:
protected $rules = [
'editing.name' => 'required',
...
'editing.client' => 'present|array',
'editing.client.*.tenant' => 'required',
];
I call the 'editModal' method where I type-hint the model and set a public property with it's attributes. Already filtered to the specific item.
Livewire component:
public function editModal(TokenCacheProvider $provider)
{
$this->editing = $provider;
$this->dispatchBrowserEvent('open-modal', ['modal' => 'edit']);
}
My blade is a simple boiler blade component:
Blade:
<div>
<x-input.group inline borderless for="name" label="Name" :error="$errors->first('editing.name')"/>
<x-input.text name="name" class="w-full" wire:model="editing.name" />
</div>
<div>
<x-input.group inline borderless for="name" label="Tenant" :error="$errors->first('editing.client.tenant')"/>
<x-input.text name="tenant" class="w-full" wire:model="editing.client.tenant" />
</div>
Once I load the page I get the following type exception
foreach() argument must be of type array|object, string given
This is because the client attribute is still a string as in the database. It should be an array as I casted it:
So, I don't understand why the client attribute is still a string and not an array as casted.
Thank you
Well it's more a work-around than a solution but Daantje found an Livewire issue on Github which might explain this behavior.
I've changed the architecture from one to two public properties. One for the actual model and a second for the json column.
Livewire component (truncated)
public MyModel $editing; // the model
public array $client; // for the json attribute
protected $rules = [
'editing.name' => 'required',
...
'client.foo' => 'required',
'client.bar' => 'required',
'client.baz' => 'required',
...
];
public function editModal(MyModel $model)
{
$this->editing = $model;
$this->client = json_decode($model->client,true);
$this->dispatchBrowserEvent('open-modal', ['modal' => 'edit']);
}
public function save()
{
$this->validate();
$this->editing->client = json_encode($this->client);
$this->editing->save();
$this->dispatchBrowserEvent('close-modal', ['modal' => 'edit']);
$this->event('Saved', 'success');
}
Two blade input field examples:
<!-- ORM field(s) -->
<div>
<x-input.group inline borderless for="name" label="Name" :error="$errors->first('editing.name')"/>
<x-input.text name="name" wire:model="editing.name" />
</div>
<!-- Json field(s) -->
<div>
<x-input.group inline borderless for="foo" label="Foo" :error="$errors->first('client.foo')"/>
<x-input.text name="foo" wire:model="client.foo" />
</div>
Well, this works but as mentioned it's more a workaround

Laravel 8: SQLSTATE[HY000]: General error: 1364 Field 'answer' doesn't have a default value

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 am getting error 404 in laravel website

I am registering a user for newsletter in website
so in web.php
// FrontEnd
Route::post('store/newsletter','FrontController#StoreNewsletter')->name('store.newsletter');
in index.blade.php ,The form is in footer of index page
and index pages called by get
Route::get('/', function () {return view('pages.index');});
<form action="{{ route('store.newsletter') }} " method="post" class="newsletter_form">
#csrf
<input type="email" class="newsletter_input" required="required"
placeholder="Enter your email address" name="email">
<button class="newsletter_button" type="submit">Subscribe</button>
</form>
I even tried changing button to input in form
this is FrontController.php which is in app/Http/Controller/
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class FrontController extends Controller
{
public function StoreNewsletter(Request $request)
{
dd($request->all());
$validateData = $request->validate([
'email' => 'required|unique:newsletters|max:55',
]);
$data = [];
$data['email'] = $request->email;
DB::table('newsletters')->insert($data);
$notification = [
'messege' => 'Thanks For Subscribing',
'alert-type' => 'success',
];
return Redirect()->back()->with($notification);
}
}
This __construct i have put after error for debug purposes
This is my table name
Schema::create('newsletters', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email');
$table->timestamps();
});
after putting dd() in exceptions/handler.php:
web.php content
//Newsletter
Route::get('admin/newsletter','Admin\Category\CouponController#Newsletter')-
>name('admin.newsletter');
// FrontEnd
Route::post('store/newsletter','FrontController#StoreNewsletter')-
>name('store.newsletter');
JorgeMudry 11:26 PM
#aakash sharma I've use your code from stackoverflow and it is working for me. your problem is elsewhere
You might need to add a GET method
in the web.php file
Route::get('store/newsletter','FrontController#viewNewsletter')->name('view.newsletter);
In FrontController
public function viewNewsletter()
{
return view('path to your view file');
}

Laravel model not working

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

Laravel 5 not storing checkbox value

We are having a strange issue with Laravel 5 in that it is refusing to store the checkbox value.
We are adapting the existing registration form that comes bundled with Laravel 5 and we are adding an optin checkbox but it seems the model does not recognise this as a field even though we are adding it as a field in the migration file.
Any help on this would be appreciated.
Mirgration File:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('password', 60);
$table->date('dob');
$table->boolean('optin')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Then we add it to the register.blade.php file:
<div class="form-group">
<label class="col-md-4 control-label">Optin</label>
<div class="col-md-6">
<input type="checkbox" class="form-control" name="optin">
</div>
</div>
At the point of creating the User model, we check the value of the checkbox and assign it.
protected function create(array $data)
{
//this does return 1 or 0 as expected
$optin = ($data["optin"] == "on") ? 1 : 0;
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'dob' => $data['dob'],
'optin' => $optin
]);
}
But at this point the field is null. No value is entered into the database...
Have you put the field 'optin' in the $fillable array within the model? Otherwise you cant create a User with 'optin' using the static create method.
//File: User.php
protected $fillable = ['optin'];
The model already has a static create() function. Therefore, when you make a call like User::create($data) from your controller, your function is not called.
My approach is to change the name of your function and make it static.
Update
Also you can override the create function:
public static function create(array $attributes)
{
$attributes["optin"] = ($attributes["optin"] == "on") ? 1 : 0;
return parent::create($attributes);
}

Categories