Post request in laravel8 not functioning - post

Get request is working fine. But when i try to create a post through POST request it's giving the following error....
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `posts` (`title`, `content`, `updated_at`, `created_at`) values (?, ?, 2021-03-22 06:05:00, 2021-03-22 06:05:00))
Here is my database table name: id title content created_at
Post model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $table="posts";
protected $fillable=[
"title",
"content"
];
};
database:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
api route:
Route::get('/posts', function(){
return Post::all();
});
Route::post('/posts', function(){
return Post::create([
"title" => request('title'),
"content" => request('content'),
]);
});

I suggest you check if you're receiving correct data from request() method
Route::post('/posts', function(){
dd(request('title'));
The other way you can try it is
Route::post('/posts', function(Request $request){
return Post::create([
"title" => $request->get('title'),
"content" => $request->get('content'),
]);
});
Greetings

Related

OneToMany relation with nested ManyToOne relation returns broken relation entity

I'm creating a structure where I have Repositories, Contributions and Users.
A repository has multiple contributions done by different users. It is important that I know the count property on the contribution.
But when I create a new Repository entity without connections I get weird behaviour.
Example Code
My index.ts:
import "reflect-metadata";
import {createConnection, getRepository} from "typeorm";
import {Repository} from "./entity/Repository";
createConnection().then(async connection => {
const newRepo = new Repository();
newRepo.name = 'test';
newRepo.description = 'no contributions made';
await connection.manager.save(newRepo);
const RepoRepository = getRepository(Repository);
const repos = await RepoRepository.find();
console.log(repos);
console.log(repos[0].contributions);
await connection.manager.save(repos);
connection.close();
}).catch(error => console.log(error));
my console output:
repos [ Repository {
name: 'test',
description: 'no contributions made',
contributions: [ [Contribution] ] } ]
contributions [ Contribution { count: null, user: null } ]
which is weird because I never created any contributions.
And the connection.manager.save(repos); call errors out on:
{ QueryFailedError: ER_BAD_NULL_ERROR: Column 'count' cannot be null
at new QueryFailedError (D:\GitHub\Issue\src\error\QueryFailedError.ts:9:9)
at Query.<anonymous> (D:\GitHub\Issue\src\driver\mysql\MysqlQueryRunner.ts:164:37)
at Query.<anonymous> (D:\GitHub\Issue\node_modules\mysql\lib\Connection.js:502:10)
at Query._callback (D:\GitHub\Issue\node_modules\mysql\lib\Connection.js:468:16)
at Query.Sequence.end (D:\GitHub\Issue\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query.ErrorPacket (D:\GitHub\Issue\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)
at Protocol._parsePacket (D:\GitHub\Issue\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (D:\GitHub\Issue\node_modules\mysql\lib\protocol\Parser.js:76:12)
at Protocol.write (D:\GitHub\Issue\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (D:\GitHub\Issue\node_modules\mysql\lib\Connection.js:91:28)
message: 'ER_BAD_NULL_ERROR: Column \'count\' cannot be null',
code: 'ER_BAD_NULL_ERROR',
errno: 1048,
sqlMessage: 'Column \'count\' cannot be null',
sqlState: '23000',
index: 0,
sql:
'INSERT INTO `contribution`(`count`, `repositoryName`, `employeeGithub`) VALUES (NULL, \'test\', NULL)',
name: 'QueryFailedError',
query:
'INSERT INTO `contribution`(`count`, `repositoryName`, `employeeGithub`) VALUES (?, ?, ?)',
parameters: [ null, 'test', null ] }
My Entities:
#Entity()
export class Repository {
#PrimaryColumn()
name: string;
#Column("text")
description: string;
#OneToMany(type => Contribution, contribution => contribution.repository, {eager: true, cascade: true})
contributions: Contribution[];
}
#Entity()
export class Contribution{
#ManyToOne(type => Repository, repository => repository.contributions, {primary: true})
repository: Repository;
#ManyToOne(type => User, user => user.contributions, {eager: true, cascade: true, primary: true})
#JoinTable()
user: User;
#Column()
count: number;
}
#Entity()
export class User{
#PrimaryColumn()
github: string;
#OneToMany(type => Contribution, contribution => contribution.user)
contributions: Contribution[];
}
What I tried:
Removing the eager on the ManyToOne from Contribution to User fixes the error and I correctly get an empty contributions array. But it isn't really a solution for the repositories that do have contributions.
The main question is: Am I doing it wrong or is this not something that works in typeorm?

Cannot send GraphQL query from Apollo Client to Rails GraphQL backend

I'm using Rails as GraphQL backend using plugin graphql-ruby. On front end size, I'm using Apollo Client for my react/redux project.
Here is my front end side:
const networkInterface = createNetworkInterface({
uri: 'http://localhost:4001/graphql',
});
export const apolloClient = new ApolloClient({ networkInterface });
On my backend, I have tested successfully following query on http://localhost:4001/graphiql.
query{
allAuthors{
full_name,
books{
book_name,
book_description,
isbn
}
}
}
Here is my rails route config:
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end
post "/graphql", to: "graphql#execute"
I try to get similar data from front end side. Here is my code:
const ALL_AUTHORS_QUERY = gql`
query allAuthors {
full_name,
books{
book_name,
book_description,
isbn
}
}
`;
apolloClient
.query({
query: ALL_AUTHORS_QUERY,
})
.then(response => console.log(response.data));
}
But after that, I meet following exception:
POST http://localhost:4001/graphql 422 (Unprocessable Entity)
Please tell me what have I wrong ? Thanks
#Edit 1:
I also try different query on client but the problem still same.
const ALL_AUTHORS_QUERY = gql`
query {
allAuthors {
full_name
books {
book_name
book_description
isbn
}
}
}
`;
apolloClient
.query({
query: ALL_AUTHORS_QUERY,
})
.then(response => console.log(response.data));
On the client side, you have named your query allAuthors when allAuthors is a GraphQL type. You don't have to name your query that's optional. However, allAuthors is a required type of the query root.
query allAuthors { your query starts with this, when it should be like this query { allAuthors

Parse Omniauth JSON response. Hash key is variable, do not know how to access

I am receiving JSON data from Omniauth and parsing it into a hash, however the data is formatted such that the user ID, changed to "USER_ID" in the code below, is the key. I need to access the data to add uid, name, email etc to make it accessible by the rails app, however I'm not sure how to do so since the key (USER_ID) will change with each user.
Any help or suggestions would be greatly appreciated.
Here is the raw JSON output:
{
"count":1,
"users":{
"123":{
"full_name":"Bob",
"email_address":"bob#bob.com",
"id":"123"
}
},
"results":[
{
"key":"users",
"id":"123"
}
]
}
The following is the output as it is currently processed.
{
"provider" =>"omniauth_provider",
"uid" =>"",
"info" => {
"name" =>nil,
"email" =>nil
},
"credentials" => {
"token" =>"987654321",
"expires" =>false
},
"extra" => {
"raw_info" => {
"count" =>1,
"users" => {
"USER_ID" => {
"full_name" =>"Bob"
"email_address" =>"bob#bob.com",
"id" =>"123"
}
},
"results" => [
{
"key" =>"users",
"id" =>"123"
}
]
}
}
}
You can convert the JSON to a hash, and then use values to access the hash values, if it's guaranteed that there's always at most 1 results return, you can use this code:
require 'json'
response = %Q(
{
"count":1,
"users":{
"123":{
"full_name":"Bob",
"email_address":"bob#bob.com",
"id":"123"
}
},
"results":[
{
"key":"users",
"id":"123"
}
]
}
)
h = JSON.parse(response)
user_info = h["users"].values.first
user_info["full_name"]
user_info["email_address"]

JQuery Datatables and ASP.NET MVC Parameter to ActionResult

I'm trying to return a View with a Jquery datatable, whose action is launched from a previous page with the ActionLink--
#Html.ActionLink("View Audit", "Audit", new { id= Model.ID })
The Jquery datatable is then pre-filtered with the ID passed from the Model ID.
Here is my JS file...(incidentally, a static value e.g. 10005 works here in the fnServerParams, but I need the value to be dynamic based on whatever Model ID is chosen from theprevious screen)
var oTable = $('#myAuditTable').dataTable({
"sAjaxSource": "GetAuditLog",
"fnServerParams": function ( aoData )
{ aoData.push({ "name": "ID", "value": 10005 })
},
"aoColumns": [
....
Here is my Audit.cshtml page.
#model IEnumerable<Models.AuditLog>
<table id="myAuditTable" width="100%">
<tr>...</tr>
</table>
and in the Controller
public ActionResult GetAuditLog(int ID){
var logs = db.AuditLog.Where(c => c.ID == ID).ToList();
var result = from c in logs
select new[] { ....
};
return Json(new
{
aaData = result
}, "text/x-json", JsonRequestBehavior.AllowGet);
}
So I normally would pass a parameter in MVC like so:
public ActionResult Audit(int ID)
{
return View();
}
But since the GetAuditLog is the action getting results, how do I get the int ID to the GetAuditLog action in order to pass the filter the records, which in turn get passed as JSON. I can't call GetAuditLog in the ActionLink, because its job is to pull JSON, not render a View.
I'm not sure what I'm missing. I've gone through this guy's articles cause they are pretty comprehensive as far as integrating ASP.NET and datatables.
http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
But cannot find an exact fit to my problem.
This post seems to come close...
How do I access the JQuery DataTables plugin aoData values in MVC3?
But doesn't quite apply since he seems to be working with a successfully passed-in parameter.
Thanks for any help.
Hi you can achieve this by two ways:
First create a hidden field having value from Model.Id and then assign this hidden field value to your datatable() function in like this
in view:
<input type="hidden" id="ID" value="#Model.ID" name="ID" />
and then put your below peace of code under document.ready and assign value ID from hidden field like this :
$(document).ready(function(){
var oTable = $('#myAuditTable').dataTable({
"sAjaxSource": "GetAuditLog",
"fnServerParams": function ( aoData )
{ aoData.push({ "name": "ID", "value": $("#ID").val() })
},
"aoColumns": [
....
});
Second: Put your datatable() function in your view under script tag and assign Model.Id directly like this:
<script type="text/javascript">
var oTable = $('#myAuditTable').dataTable({
"sAjaxSource": "GetAuditLog",
"fnServerParams": function ( aoData )
{ aoData.push({ "name": "ID", "value": '#Model.ID' })
},
"aoColumns": [
....
</script>
Hope this will resolve this issue.

symfony Doctrine migration adding boolean column and field length

I have a symfony 1.4 project and I am adding a new column via a migration. The new column in schema.yml looks like this:
has_private_data: { type: boolean, notnull: true, default: false }
The migration that gets generated looks like this:
<?php
/**
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Version26 extends Doctrine_Migration_Base
{
public function up()
{
$this->addColumn('device', 'has_private_data', 'boolean', '25', array(
'notnull' => '1',
'default' => '0',
));
$this->addColumn('device_history', 'has_private_data', 'boolean', '25', array(
'notnull' => '1',
'default' => '0',
));
}
public function down()
{
$this->removeColumn('device', 'has_private_data');
$this->removeColumn('device_history', 'has_private_data');
}
}
Why it the length of this boolean field being set to 25? (My backend database is MySql.)
You can be save by ignoring that. In doctines Table.php on line 1361 you can find that if the type is booelan the length will be fixed to 1.
case 'boolean':
$length = 1;

Resources