I have input request from controller as below code.
public function CreateSave(Request $request){
return $request;
}
Below are printed inputs request.
{
_token: "jf9SQUP48wrPz9LBT8ItZ76UHOc4lD6ot3HrF0bB",
hn: null,
prefix: "1",
name: john,
lastname: doe,
room: "1",
custom_1154: "100",
custom_51741: "99660"
}
But, I would like to get only input contain specific string 'custom_'. So result should be like this.
{
custom_1154: "100",
custom_51741: "99660"
}
I may use foreach loop but I'm not sure other smart way capable. Any advise or guidance would be greatly appreciated, Thanks.
I have tried something, see this is helping you.
$collection = collect($request->all())->reject(function($item, $key){
if (strpos($key,'custom_') !== false) {
return false;
} else {
return true;
}
})->toArray();
Related
I have the user image saved on a different table and I want to have the following in User model
public function Image()
{
return $this->hasOne(UserImages::class, 'user_id', 'id')->latest();
}
The above relation returns the following.
"image": {
"id": 3,
"user_id": 1,
"image": "http://live.test/uploads/user/User-Oss8MewXVzHZCehHoOUgkdYoo3N1K0gYI9jY69ZsnyiHnqHsHv.png",
"is_primary": 1,
"created_at": "2021-04-12T08:01:47.000000Z",
"updated_at": "2021-04-12T08:01:47.000000Z"
},
I want to receive only image, how can I do that?
use value() method
$user->image()->value('image');
From Eloquent documentation
If you don't need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
You can set it as a user attribute.
public function getProfileImageAttribute()
{
return optional($this->image)->image;
//or
return $this->image->image ?? null;
//or
return $this->image->image ?? 'path/of/default/image';
}
now you can call it like this
$user->profile_image;
You can create another function inside your model and access the previous method like
public function image()
{
return $this->hasOne(UserImages::class, 'user_id', 'id')->latest();
}
public function avatar()
{
return $this->image->image ?: null;
//OR
return $this->image->image ?? null;
//OR
return !is_null($this->image) ? $this->image->image : null;
//OR
return optional($this->image)->image;
}
And it will be accessible with $user->avatar();
As from discussion you are sending response to api
$this->user = $this->user->where('id', "!=", $current_user->id)->with(['chats','Image:user_id,image'])->paginate(50);
This will help you, but it will be better to use Resources for api responses to transform some specific fields.
You could use the magic Laravel provided:
$user->image->pluck('profile_image');
Documentation: https://laravel.com/docs/8.x/collections#method-pluck
I have following code:
// User.php
public function groups() {
return $this->belongsToMany(
Group::class,
'group_user',
'user_id',
'group_id',
'id'
);
}
// Group.php
public function users() {
return $this->belongsToMany(
User::class,
'group_class',
'group_id',
'user_id',
'id'
);
}
And in routes/web.php
Route::get('/test', function () {
$me = App\User::first();
$group = App\Group::with('users')->first();
foreach ($group->users as $user_index => $user) {
// Show all users (a.k.a members) of this group, except myself
if ($user->id == $me->id) {
unset($group->users[$user_index]);
}
}
return $group;
}):
Result:
{
"id": 1,
"name": "ABC Group",
"users": { // This should be array right?
"1": { // This should be start with 0
"id": 2,
"name": "...",
"email": "...",
},
"2": { // This should be 1
"id": 3,
"name": "...",
"email": "...",
}
}
}
What I have tried:
#1 Put values() in the end of foreach loop, like:
foreach ($group->users as $user_index => $user) {
// Show all users (a.k.a members) of this group, except myself
if ($user->id == $me->id) {
unset($group->users[$user_index]);
}
$group->users->values(); // Not working
}
#2 Put values() after the foreach loop, like:
Route::get('/test', function () {
$me = App\User::first();
$group = App\Group::with('users')->first();
foreach ($group->users as $user_index => $user) {
// Show all users (a.k.a members) of this group, except myself
if ($user->id == $me->id) {
unset($group->users[$user_index]);
}
}
$group->users->values(); // Still not working
return $group;
}):
Expected result:
{
"id": 1,
"name": "ABC Group",
"users": [ // Array
{ // index 0
"id": 2,
"name": "...",
"email": "...",
},
{ // index 1
"id": 3,
"name": "...",
"email": "...",
}
]
}
Q: How to reindex collection array in eager loading after using unset()?
Thanks in advance
You've got a few things to unpack here that might help you.
First, your query returns a Laravel collection of users attached to the single model Group. Laravel has a bit of magic in the background that allows for array notation as well, but probably easiest to think about this as a collection for your purposes. In some cases, you can translate this to an array using Laravel's toArray() method, something like:
$userArray = $group->users->toArray();
For dropping an index, or in this case a user from the Group's users, take a look at the forget() method, which works on the collection object.
However, I think you may wish to come at this from the reverse... Pull the unwanted index(es) in a single query, rather than having to loop through the collection after the fact. Something like this may be of value to you:
$me = App\User::first();
$group = App\Group::with(['users' => function($query) use($me){
$query->where('users.id', '!=', $me->id);
}])->first();
This query will remove the unwanted user from the collection right out of the database, eliminating the need for additional code, which is what I think you were after.
HTH.
So before everything this is not duplicate.
I've got a callback method which will get 2 parameters from payment getway. the function they gave us need Amount to make sure everything is correct and base on Amount they gonna gave us payment status, but they won't post it, i should get it from my Database which i've did base on this code :
public function order(Request $request){
$MerchantID = 'xxxxxxxxxxx';
$Authority =$request->get('Authority') ;
$Amount = Invoice::select('invoice_balance')->where('authority',$Authority)->get();
if ($request->get('Status') == 'OK') {
$client = new nusoap_client('https://www.localhost.com/pg/services/WebGate/wsdl', 'wsdl');
$client->soap_defencoding = 'UTF-8';
$result = $client->call('PaymentVerification', [
[
'MerchantID' => $MerchantID,
'Authority' => $Authority,
'Amount' => $Amount,
],
]);
if ($result['Status'] == 100) {
return 'Done.';
} else {
return 'Error with 1';
}
}
else
{
return 'Error with 2';
}
// return $Amount;
}
when i use this code i get The Response content must be a string or object implementing __toString(), "boolean" given. which i'm pretty sure it's just about Amount part, because when use manual value for Amount (exact amount of cart in $Amount = amount), it's gonna gave me The Response content must be a string or object implementing __toString(), "boolean" given. Error.
I've also tried someways in other questions but didn't worked. if u remove whole if(status... part and only return $Amount to make sure it work it gonna gave [{"invoice_balance":"2000"}] which i don't know if this is my mistake or not. please help me, i'm in learning process.
Invoice Model(if needed):
class Invoice extends Model {
protected $fillable = [
'from_user_id', 'to_user_id', 'invoice_title', 'invoice_description', 'invoice_balance', 'invoice_due_date', 'status'
];
protected $hidden = [
'authority'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
well the solution was changing
$Amount = Invoice::select('invoice_balance')->where('authority',$Authority)->get();
to
$Amount = Invoice::select('invoice_balance')->where('authority',$Authority)->value('authority');
Need more information:
Do this and tell me what the output is:
public function order(Request $request){
dd($request->input());
}
I am trying to learn Vue.js that consumes an API build with Laravel. The idea is simple, a user can make a post and a post can have comments. I can get the relationships working within laravel, but I can not figure out how to return the author name of the post or comment with Vue.js.
When using the blade templating engine I use something like this in a foreach loop for returning the Author name:
{{ $post->user->name }}
When I return the posts trough an API I get don't get any user information, except for the user id. How can I get the user information that belongs to this post?
{
"message": "Success",
"data": [
{
"id": 1,
"body": "test body 1",
"user_id": "1",
"created_at": "2016-09-16 10:22:57",
"updated_at": "2016-09-16 10:22:57"
}
]
}
<script>
export default {
/*
* The component's data.
*/
data() {
return {
posts: [],
};
},
/**
* Prepare the component.
*/
ready() {
this.getPosts();
},
methods: {
/**
* Get Posts.
*/
getPosts: function() {
this.$http.get('/api/wall/posts')
.then(response => {
this.posts = response.data.posts;
});
}
}
}
</script>
public function getPosts($id = null)
{
if (!$id){
$data = Post::all();
$message = 'Success';
$code = 200;
} else {
$data = Post::FindOrFail($id);
$message = 'Success';
$code = 200;
}
return Response::json(['message' => $message, 'data' => $data], $code);
}
You may use eager loading for that:
Post::with('user')->FindOrFail($id);
Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.
I have this
if($this->_submit_validate_comment() == false) {
$this->post(); return;
}
function _submit_validate_comment() {
$this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
return $this->form_validation->run();
}
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).
For example:
http://yoursite.com/forum/topic/12
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
redirect('/forum/topic/'. $topic_id);
}
Or
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
$this->topic($topic_id);
}
Hope this helps.
Thanks for helping i can see what you mean but it just dont work :b,
i have this
$topic_id = $this->uri->segment(3);
$this->post($topic_id);
return;
and my url is
localhost:8888/ci/index.php/forum/create_comment
it looks like it cant find the ID
my URL to the forum is
localhost:8888/ci/index.php/forum/post/33
this is my functions
function create_comment() {
if($this->_submit_validate_comment()
== false) { $id = $this->uri->segment(3);
$this->post($id); return;
//echo "validate fejl, kontakt lige
en admin!"; } else { $data =
array( 'fk_forum_traad' =>
$this->input->post('id'),
'brugernavn' =>
$this->session->userdata('username'),
'indhold' =>
$this->input->post('kommentar'),
'dato' => 'fejl' );
$this->load->model('forum_model');
$this->forum_model->create_comment($data);
redirect('/forum/post/'.
$this->input->post('id').'',
'refresh'); }
}
function post($id) {
$this->load->model('forum_model');
$data['query'] =
$this->forum_model->posts($this->uri->segment(3));
$this->load->model('forum_model');
$data['comments'] =
$this->forum_model->comments($this->uri->segment(3));
$data['content'] = 'forum_post_view';
$this->load->view('includes/template',
$data); }
Why not pass in the return uri in the form submission using a hidden input field? No additional work will be needed by the controller other than validation of the return uri before performing a redirect.
Place the validation error string in session class's flashdata for echoing out in the form, along with any other data used to pre-populate your form)