Laravel 5: Check if post input query exists - laravel

In Laravel you can get all the post data like so:
$request->post();
You can also check if a form has the GET or POST query like so:
$request->has('foo');
However, how do I check if a form has a POST query. Note that I'm aware you can do the following:
$request->post('foo') !== null;
but foo can sometimes be null if the data being posted is JSON. e.g.
{
"foo": null
}

To answer my own question, a solution that I found worked quite well is as follows:
$postData = $request->post();
array_has($postData, 'foo');
The advantage of this approach is that you can also use dot notation like you can with $request->has().
Any alternative solutions is welcome.

Related

Method Illuminate\Database\Eloquent\Collection::orderby does not exist

$posts = Post::all()->orderby('created_at','desc')->where('usr_id','=',session('LoggedUser'))->get();
return view('admin.profile',compact('userInfo' , 'posts'));
i am making a custom auth for a journal activity but i cant sort the content i shows this error
"Method Illuminate\Database\Eloquent\Collection::orderby does not exist. "
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();
True query like that. When you take all() already query done.
Change it to:
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();
you cant use all() and orderBy because all() does not allow the modification of the query.
I believe this might be because you typed orderby instead of orderBy (notice the uppercase). See laravel orderBy documentation if needed.
Plus, as mentionned by other, don't use all() if you need to do other thing (where clause, order by, etc) in you query.
Change the orderby to orderBy. This could be the reason you are getting the error.
$posts = Post::all()->orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->get();
return view('admin.profile',compact('userInfo' , 'posts'));
Or...
If you want to get specific number of posts you can do it this way to avoid using the Post::all
$posts = Post::orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->paginate(5);
return view('admin.profile',compact('userInfo' , 'posts'));
Yeah this is pretty confusing and just got me as well.
The actual problem isn't the capitilization typo (orderby versus orderBy) but rather the fact that you're using ->all() instead of just Model::orderBy()->...
The moment you use ->all() the object is transformed to another type of collection object and the normal methods one would expect do not exist.
In this case you should rather use sortBy().
See here.

Laravel 5.5 - findorFail and check for another value

I am using try in Laravel 5.5 like this...
try {
$fruit = Fruit::findOrFail($id);
}
But I would like to check that not only that it finds the Fruit with the supplied ID but that it also has a fruit_color of 'red'
Do I need to do this with a 'with' statement?
I know I can run another check afterwards but wondered if I could do this all in one statement?
A few things. First, throwing an exception here is the wrong way to handle the ‘if’ situation. If you plan on a situation where a value isn’t return, then this isn’t the proper use of an exception. To answer your question:
$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->get();
This returns a collection of items meeting your criteria. Next to test if the collection is empty (no fruit) you can do the following:
if($fruit->isEmpty()) {
//handle empty collection
}
Hope this helps! The Laravel documents for collections kicks a**. I’d recommend reading further there.
You just need to add your extra conditions in before you call the find:
try {
$fruit = Fruit::where('fruit_color', 'red')->findOrFail($id);
}
Try this code
$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->first();

How to use one to many relation query in parse.com?

I have the 2 classes one is post and other is comments
=> One post has many comments
And i want to result like this
results:[ {
post_title:'post1',
date:'..',
postcomments:[
{comment1},
{comment2},...]
},
{
post_title:'post2',
date:'..',
postcomments:[
{comment1},
{comment2},...]
}
]
The easiest would be to use Lists: The Post object has a property postcomments that is a list of Comment objects. You could query then as follows (javascript):
new Parse.Query("Comment")
.include("postcomments")
This will give you a list of Post objects. Each Post object will have a list of associated Comment objects which you can access like this: post.get("postcomments")
If you expect to usually have more than 100 or so comments for one post you can also use Parse relations. The advantage here is that the comments are not always fetched together with the post thus saving data.

Rethinkdb filter on an earlier query

I have a table "posts" with "timestamp".
Now I want from all user that have more than 1 post, to get all posts EXCEPT the most recent post.
With this query I can successfully check the users who have more than 1 post:
r.table("post")
.group('userId')
.count()
.ungroup()
.filter(r.row("reduction").gt(1))
I can get the last post of a specific user by doing
r.table("post")
.filter({userId: 'xxx'})
.max('timestamp')
Now I need to tie those somehow together, and then compare the timestamp from each row with the max('timestamp') to see if they are not equal. The following is what I had but it's obviously wrong
.filter(r.row('timestamp').ne(r.row('timestamp').max('timestamp')('timestamp')))
Any advice how I bring all this together?
Something like this ought to work:
r.table('post')
.group({
index: 'userId'
})
.ungroup()
.filter(function(doc) {
return doc('reduction').count().gt(1)
})
.group('group')('reduction')
.nth(0)
.orderBy(
r.desc('timestamp')
).skip(1)
With reservations for syntax errors; I built this query using python and then converted it to javascript. Especially unsure about the .nth(0) part, never used it in javascript. In python it's just [0].

Codeigniter: Passing form data from view to controller

Which is right? notice in the second option, I'm passing the form values using the $_POST variable. Whereas the first option, I call and assign variables for each form field.
I've seen this ...
<validation code> ....
$todo = array(
'name'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->Todo_model->add($todo);
But I've also seen the following ...
$records['email'] = "trim|required|min_length[4]|xss_clean";
...
...
$this->validation->set_rules($records);
if ($this->validation->run())
{
$this->account_model->saveAccountSettings("sam", $_POST);
$this->session->set_flashdata('message', 'Done!');
redirect('account/settings');
} else {
...
}
I tend to use a mix of your two examples. I'm pretty sure things like trim won't modify the actual post data, so you can only take advantage of it if you go through the validation framework to get the data. I actually never access POST directly anymore using CI.
Plus I'd be worried in your second example about just shoving POST into my model. What happens if someone clever adds "lastname" to the post data sent in and your db column is named the same? Even though you weren't expecting to deal with that data now you've got unvalidated data coming in. That's why I employ part of your first example and manually pull out the items I want to save into an array first.
So I'd recommend a hybrid.
Normally my code looks something like this:
$fields['email'] = "trim|required|valid_email|min_length[4]|xss_clean";
...
...
$this->validation->set_rules($fields);
if ($this->validation->run())
{
$account = new array();
$account['id'] = $accountId; //wherever you get the Id from
$account['email'] = $this->validation->email;
$this->account_model->save($account);
$this->session->set_flashdata('message', 'Done!');
redirect('account/settings');
} else {
...
}
The first option is better easy to read or trace
Pass values using post variables is better option
What the real benefit to use this
$account['email'] = $this->validation->email;
Instead of
$account['email'] = $this->input->post('email');

Resources