hi guys i'm making an api in laravel 4 !! so im getting data that i store and return a json response everyting is good but just one thing :)
this is part of th code that return a response
if( $user->save() )
{
$id = DB::table('users')
->where('pseudo','LIKE',$pseudo)
->select('id')
->get();
return Response::json(array(
'status' => 'ok',
'message' => 'success',
'userId' => $id
));
}
the reponse is
{"status":"ok","message":"success","userId":[{"id":11}]}
but i whant to get this response
{"status":"ok","message":"success","userId":11}
how can i do it im trying but nothing chaged ! thx
You are setting 'userId' equal to the entire $id object returned from the query. You really just want
return Response::json(array(
'status' => 'ok',
'message' => 'success',
'userId' => $id['id']
));
Just something a little bit neater:
$id = DB::table('users')
->where('pseudo','LIKE',$pseudo)
->pluck('id'); // Retrieve first result, column 'id'
Related
So i have 2 APIs for the relational table. I build the API using Laravel.
Here's the code for the one without the id.
public function Berita()
{
$berita = Berita::with('Kat_Berita', 'Pengguna')
->select(
'id',
'judul',
'kategori_id',
'isi',
'gambar',
'tgl',
'user_id'
)->get();
return response()->json([
'message' => 'Data berita With kategori & pengguna Loaded Successfully',
'berita' => $berita
], Response::HTTP_OK);
}
The one without the ID works just fine, but with the ID, it says like this
here's the code for that.
public function BeritaById($id)
{
$berita = Berita::with('Kat_Berita', 'Pengguna')
->select(
'id',
'judul',
'kategori_id',
'isi',
'gambar',
'tgl',
'user_id'
)
->where('id', $id)
->get();
return response()->json([
'message' => 'Data berita With kategori & pengguna Loaded Successfully',
'berita' => $berita
], Response::HTTP_OK);
}
How to handle SyntaxError: Unexpected token R in JSON at position 0 for this?
Here is my store function
public function store(Request $request)
{
$post = new Post();
$post->author()->associate(auth()->user());
$post->fill($request->all());
$post->save();
return response()->json($post);
}
As a response i get:
I don't want all the data so I tried to take only the data I have defined like this:
$post = $post->only([
'id',
'title',
'content',
'published_at',
'author'
]);
And response now is:
Much better, but not completely. I can not define post author data in this way.
The only way is by creating a creepy relationship where you select only necessary data or like this:
$post = [
'id' => $post->id,
'title' => $post->title,
'content' => $post->content,
'published_at' => $post->published_at->toDateTimeString(),
'author' => [
'id' => $post->author->id,
'name' => $post->author->name,
'email' => $post->author->email,
]
];
So my question is... maybe there is more elegant way to achieve this.
Thank you very much!
The simplest way would probably be to just use only with the author as well:
return $post->only('id', 'title', 'content') + [
'author' => $post->author->only('id', 'name', 'email'),
];
If it was going to get any more complicated or reused somewhere else then I would suggest using something like Eloquent Resources
I would add a function to your Post model
public function jsonOutput()
{
$array['id'] = $this->id;
$array['title'] = $this->title;
$array['content'] = $this->content;
$array['author'] = [
'id' => $this->author->id,
'name' => $this->author->id
];
return $array;
}
and then call it like this
return response()->json($post->jsonOutput());
When doing
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
The response is
)]}'
["uvresp","03AJpayVHarkP_b40i5...stuff...VOrIy6m3ws",1,120]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The )]}' breaks things. I have no idea where that is coming from.
$g_recaptcha_response looks fine to me (what I am sending to google to verify).
The function to verify recaptcha
function verify_recaptcha ($g_recaptcha_response, $remote_address) {
# Verify captcha
$post_data = http_build_query(
array(
'secret' => 'secret',
'response' => $g_recaptcha_response,
'remoteip' => $remote_address
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
return $result->success;
}
Thanks.
Ok my bad. The above code works, I had a problem further downstream (query was trying to use a column that did not exist).
I'm new to cakephp2 and mysql and need some help.
I want to get the data from yesterday and daybefore yesterday date from the same Model in cakephp2,
However the conditions will be different so I am trying to get the data by making two different methods that contains the find() with different conditions. ,however,I'ts not working. Here is the sample below ↓
This method getYesterday() will return the data as a array but I want to add a condition
that will check if the pageview count is not 0, how will I do that ?
public function getYesterday() {
$yes = array();
$dt = date('Y-m-d', strtotime('-1 day'));
// $dy = date('Y-m-d', strtotime('-2 day'));
$yesterday = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as yesterday_pv'),
'conditions' => array('dt' => "2014/09/26", 'is_crawler' => 0,'count(page_view)>'=>0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($yesterday as $y) {
$yes[] = $y;
//$i++;
}
return $yes;
}
The function below will get the data from daybefore yesterday
public function getDBY() {
$dayyes = array();
$dt = date('Y-m-d', strtotime('-2 day'));
$daybefore = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as daybefore_pv'),
'conditions' => array('dt' => "{$dt}", 'is_crawler' => 0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($daybefore as $dby) {
$dayyes[] = $dby;
//$i++;
}
return $dayyes;
}
The probelem is I'm not sure about this way, Is there a better solution that you can get the different result with different conditions in mysql cakephp2 ? The main thing I want to do Is to get the yesterdays data and daybefore yesterdays data from the same model but I'm not sure how I can do this, I've checked cakes documents but cant find the solution. Sorry for my broken English.
I have a stupid little question.
As I already know a select query in Laravel will always return an array of results,
I have this query:
$id = DB::select(
'select id from users where username = ?', array(Session::get('theuser')));
by inserting this id into my table
DB::table('characters')->insert(array(
'id' => $id,
'char_name' => $charname,
'char_dynasty' => $dynastyname,
'picture' => 'Male1.png'
));
I will get the error: ksort() expects parameter 1 to be array, string given.
How can I get rid of this? Thanks in advance!
At least one of $id, $charname or $dynastyname is an array and should not be.
You are using it wrong.
Below is a POC proving this.
The output is "Warning: ksort() expects parameter 1 to be array, integer given on line 13"
It runs as expected when providing 'id' => 'a'.
function insert(array $values)
{
if ( ! is_array(reset($values)))
{
$values = array($values);
}
else
{
foreach ($values as $key => $value)
{
ksort($value); $values[$key] = $value;
}
}
var_dump($values);
}
insert(array(
'id' => array('a'),
'char_name' => 2,
'char_dynasty' => 3,
'picture' => 'Male1.png'
));