How to optimize multiple value query from database in laravel - php

I am new to laravel and using simple command to query from database.
I am trying to get multiple value from database with same id.
$id = 'P01';
//Get value from database
$fruitname = DB::table('fruits')->where('id', $id)->value('fruitname');
$fruitcolour = DB::table('fruits')->where('id', $id)->value('fruitcolour');
$fruitshape = DB::table('fruits')->where('id', $id)->value('fruitshape');
$updatedat = DB::table('fruits')->where('id', $id)->value('updated_at');
$data = array(
'fruitname' => $fruitname,
'fruitcolour' => $fruitcolour,
'fruitshape' => $fruitshape,
'updated_at' => $updatedat
);
As result, $data can store the value.
But i found out that it takes time to complete the process.
Is there any ways i can optimize the process?

I'm not sure why you're making it more hard than it is, but you can just simply use eloquent in this case:
Provided you already have created the necessary model and adding it in your controller:
use App\Fruits;
Just simply use it in the find method:
public function someMethodName()
{
$id = 'P01';
$fruit = Fruits::find($id);
echo $fruit->fruitname; // and others
}

$fruit = DB::table('fruits')->where('id', $id)->first();
$data = array(
'fruitname' => $fruit->fruitname,
'fruitcolour' => $fruit->fruitcolour,
'fruitshape' => $fruit->fruitshape,
'updated_at' => $fruit->updatedat
);
Or if you have a view, you could just do
$fruit = DB::table('fruits')->where('id', $id)->first();
return view('yourview', compact('fruit'));
And in the view, you can access each of the values like so:
{{ $fruit->fruitname }}
{{ $fruit->fruitcolor }}

In your controller add function
public function function_name(Fruit $fruit)
{
return view('your_view_name', compact('fruit'));
}
In web file set your route as
Route::get('/fruit/{fruit}','YourControllername#methodName')->name('show');
At the time of setting route
Show
in View file get data as
{{ $fruit->fruitname }}
{{ $fruit->fruitcolor }}

To make it with a single query with QueryBuilder since QueryBuilder can have better performance than Eloquent:
DB::table('fruits')->where('id', $id)
->select(['fruitname', 'fruitcolour', 'fruitshape', 'updated_at'])
->first();
This returns a associative array with the selected column names.

Related

How to Use WhereIn Query in Laravel 8

Controller
public function detail(Peserta $peserta)
{
// get konfirmasi_id
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->select('id')->get();
$payments = BankSettlement::whereIn('konfirmasi_id',array($konfirmasi->id))->get();
// dd($payments);
$tagihan = Tagihan::where([['peserta_id', $peserta->id],['type', 3]])->first();
return view('data.peserta.detail', ['data' => $peserta, 'payments' => $payments,'tagihan' => $tagihan]);
}
I want to display data from BankSettlement based on konfirmasi_id. Here I try to use WhereIn Query like this, but still error "Property [id] does not exist on this collection instance.".
$konfirmasi has data like the image above.
What is the correct way to display data from BankSettlement based on konfirmasi_id ? Thankyou
Try this changes:
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->pluck('id')->toArray();
$payments = BankSettlement::whereIn('konfirmasi_id',$konfirmasi)->get();
This is the wrong way to change a collection to array.
$payments=BankSettlement::whereIn('konfirmasi_id',array($konfirmasi->id))->get();
You should do this
public function detail(Peserta $peserta)
{
// get konfirmasi_id
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)
->select('id')
->get()
->pluck('id')
->toArray(); //This will return an array of ids
$payments = BankSettlement::whereIn('konfirmasi_id',$konfirmasi)->get();
// dd($payments);
$tagihan = Tagihan::where([['peserta_id', $peserta->id],['type', 3]])->first();
return view('data.peserta.detail', ['data' => $peserta, 'payments' => $payments,'tagihan' => $tagihan]);
}
Edit:
Read Laravel Collections|Pluck
If you do not have to reuse the result of $konfirmasi then it would be better to use subquery. Writing a subquery is optimized way. if you write two different query then there will be two seperate database connection request.
Laravel subquery
$konfirmasi = KonfirmasiPembayaran::where('email',$peserta->email)->select('id');
$payments = BankSettlement::whereIn('konfirmasi_id', $konfirmasi )->get();

Laravel eloquent does not update JSON column : Array to string conversion

I want to update a JSON column in my database but I get this error :
Array to string conversion
I have declared the column name as array in the model :
protected $casts = [
'destinations' => 'array'
];
this is the code that I use :
$data[] = [
'from' => $fromArray,
'to' => $toArray
];
Flight::where('id', $id)->update(['destinations' => $data]);
What should I do ?
You can access your json keys using the arrow so you can update your column like so:
Flight::where('id', $id)->update([
'destinations->from' => $data['from'],
'destinations->to' => $data['to']
]);
As #fubar mentioned you have to have mysql
5.7 in order to have my solution to work.
check the docs
This code did the work for me.
$user = User::where('id', $request->user_id)
->first();
$array_data = ["json_key3"=>"value"];
$user->forceFill([
'db_column->json_key1->json_key2' => $array_data
])->save();
According to this conversation on Github : Make json attributes fillable if Model field is fillable Taylor Otwell recommande the use of save method :
$model->options = ['foo' => 'bar'];
$model->save();
So in you case you can do it like this :
$flight = Flight::find($id);
$flight->destinations = $data;
$flight->save();
You're getting that error because you're trying to update your model using the Query Builder, which basically just creates raw SQL queries. It isn't aware of any data casting, etc defined within your model. You therefore have three choices:
1) Find your model, and run the update on your model instance.
$flight = Flight::findOrFail($id);
$flight->update(['destinations' => $data]);
2) Convert the data to a string before updating.
$data = json_encode($data);
Flight::where('id', $id)->update(['destinations' => $data]);
3) Use a database that supports JSON column queries, per #AmrAly's suggestion. Beware of this option, as not all databases support JSON columns.

Laravel pluck fields from relations

I have a Seller object which has a related User. I need to fill a select from LaravelCollective so I need to make something like this:
{!! Form::selectGroup('seller_id', 'Seller', Seller::with('user')->pluck('user.first_name', 'id')->toArray(), null) !!}
The problem is that I cannot take fields from relationships (user.first_name).
How can I do it?
UPDATE
I want to avoid doing this...
<?php
$sellers = [];
Seller::with('user')->get()->each(function ($seller) use (&$sellers) {
$sellers[$seller->id] = $seller->user->first_name;
});
?>
You can use Laravel's pluck method as:
$sellers = Seller::with('user')->get()->pluck('user.first_name', 'id')
try with below solution it's working for me as i am using laravel 8
$sellers = Seller::with('user')->get()->pluck('user.*.first_name')
You can achieve it by using join() & pluck() like this:
$s = Seller::join('users', 'sellers.user_id', '=', 'users.id')
->pluck('sellers.id', 'users.id')
->all();
This would give an array like this:
[
'seller_id_1' => 'user_id_1',
'seller_id_2' => 'user_id_2',
'seller_id_3' => 'user_id_3',
'seller_id_4' => 'user_id_4',
'seller_id_n' => 'user_id_n',
];
Hope this helps!
Another way to do it is to define what columns you need inside the relationship. It's good if you always need just these columns on the given relationship. Example:
Class Seller extends Model {
...
public function user()
{
return $this->hasOne(user::class, 'id')
->select('id', 'first_name');
}
}

Updating record in Laravel from a select using laravel's lists not working

In one of my laravel pages I am updating a record. The form is bound to the model, and all fields are updating properly except those where I am presenting a select using lists that populates the select from the database:
{{ Form::select('resume_id', $resume_lists) }}
I just have no idea why these will not update. They are pulling the appropriate values from mySQL. Any ideas?
Thank you.
I have my code in routes, not in a controller
Route::get('application/edit/{id}', array('as' => 'application.edit', function($id)
{
$user = Auth::user();
$company_lists = Company::where('user_id', '=', $user->id)->get()->lists('company', 'id');
$resume_lists = Resume::where('user_id', '=', $user->id)->get()->lists('name', 'id'); //changed resume to name
$companies = Company::where('user_id', '=', Auth::user()->id)->get(); //just added
//$currentintdate=$application['followupBy']; /////
Session::put('appid', $id); /////
return View::make('application-edit', array('company_lists' => $company_lists), array('resume_lists' => $resume_lists))
->with('application', Application::find($id));
}));
try this:
$resume_lists = YourResumeModel::lists('title', 'id');
{{ Form::select('resume_id', $resume_lists) }}
frist column is your text for dropdown
and next column is your row id
just var dump the resume list data in controller, make sure its available at the controller, so after you initialize the variable/array
return var_dump($resume_lists); // check if its valid array with id as key and label as value, if available, go view and do the same
Use: $resume_lists = Resume::all()->where('user_id', '=', $user->id)->lists('name', 'id');
Or: $resume_lists = Resume::where('user_id', '=', $user->id)->lists('name', 'id')->toArray();
well, my records were not updating because I had a column as not nullable and I was not passing any value while testing. I got no error at all about this so I had no idea.

Laravel returning multiple views

I'm trying to return multiple views using the laravel framework. When I return the variable, it only makes it through the loop once, therefore only one comment is displayed on the page.
foreach($index_comments as $comments){
$commentComment = $comments->comment;
$index_children = NULL;
$getUser = DB::table('users')->where('id', '=', $comments->from_user_id)->get();
foreach ($getUser as $user) {
$firstName = $user->first_name;
$lastName = $user->last_name;
}
return View::make('feeds.comments')->with(array(
'firstName' => $firstName,
'lastName' => $lastName,
'commentComment' => $commentComment,
'index_children' => $index_children
));
}
I just need a way of returning multiple views.
Thanks for any help!
Toby.
It seems that you don't quite understand the concepts of Laravel and/or PHP yet. So let's start it from scratch: We want to fetch all comments, output the comment and the name of the user who wrote the comment.
At a very basic level, we can just grab it straight from the DB with the query builder:
public function showComments()
{
$commentData = DB::table('comments')
->join('users', 'users.id', '=', 'comments.from_user_id')
->get(['text', 'firstName', 'lastName']);
return View::make('feeds.comments')->with('commentData', $commentData)
}
And in your view:
#foreach($commentData as $comment)
{{ $comment->text }}
<br />
written by {{ $comment->firstName }} {{ $comment->lastName }}
<hr />
#endforeach
That's it. You don't return the view on each iteration, the iteration happens in the view. The return statement terminates the function execution immediately. If you return within in a loop, it will always exit upon the first iteration, that's why you're getting only one result.
In the next step, you should play around with Models and Eloquent for even more powerful and readable data handling.

Categories