get all data count from relationship | Laravel - laravel

i use laravel:command for function, which is i need to know how many reviews been given to my products, i will capture my database example below:
Product fields
Reviews fields
i've already declare the relationship which is:
App\Models\Product :
public function rev()
{
return $this->hasMany(Reviews::class, 'product_id', 'id');
}
App\Models\Review :
public function prod()
{
return $this->belongsTo(Products::class, 'product_id','id');
}
and this is my command for the function:
protected $signature = 'review:product {product_id}';
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
foreach ($products as $key => $value) {
$rating = $value->rev->rating;
}
dd($products);
}
after i run my command it returns this error
Error
what i'm expecting is i could get the whole rating of specific id

You did not declare the variable $rating prior to using it.
But there is a much easier approach to your problem, since youve already setup the relationships.
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::find($id);
$ratings = $products->rev->pluck('rating');
dd($ratings);
}

Because of product can have many revs, so you can use loop for this
foreach ($value->rev as $item) {
$val = $item->rating;
}

if you are expecting to sum up all rating for particular product id, then you should declare initial number for variable $rating before foreach, then sum up with += operator :
public function handle(){
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
$rating = 0;
foreach ($products as $key => $value) {
$rating += $value->rev->rating;
}
dd($rating);
}

Related

Laravel pass value from foreach loop in controller to view

I am trying to get the data from a foreach loop in my controller to pass to my view. How do I do it?
Controller
class FormteachersController extends Controller
{
public function form_teachers_view(){
$UniqueStudent = Student::where('Student_ClassID','JSS 1C')->get();
foreach ($UniqueStudent as $keydata) {
$student = $keydata->Stud_id;
$result= Result::where('Term_ID','1st Term')->where('Student_ID',$student)->where('Class_ID','JSS 1C')->where('Session_ID','2225/2222')->get();
foreach ($result as $keyresult) {
echo '<br>'.'<br>'.$student.'-'.$result;
}
return view('teachers.form_teachers_comment_sec');
}
}
}
This is the output.
You can do something like this:
class FormteachersController extends Controller
{
public function form_teachers_view(){
$uniqueStudent = Student::where('Student_ClassID','JSS 1C')->get();
$uniqueStudentsData = [] ;
foreach ($uniqueStudent as $keydata) {
$student = $keydata->Stud_id;
$result = Result::where('Term_ID','1st Term')->where('Student_ID',$student)->where('Class_ID','JSS 1C')->where('Session_ID','2225/2222')->get();
foreach ($result as $keyresult) {
$uniqueStudentsData[] = '<br>'.'<br>'. $student.'-'. $keyresult;
}
}
return view('teachers.form_teachers_comment_sec', compact('uniqueStudentsData'));
// or pass array
return view('teachers.form_teachers_comment_sec',[
'uniqueStudentsData' => $uniqueStudentsData,
]);
}
}
Now, in your form_teachers_comment_sec.blade.php, run your foreach loop and do what do you want to there
// $uniqueStudentsData
#foreach($uniqueStudentsData as $data)
// do what do you want
#endforeach
Hopefully, it will be work. more documentation please visit laravel documentation

error while update method on boolean

I am trying to update method in Laravel but error is:
"Call to a member function tradereason() on boolean"
I also check same question of other people asked but there're a lot of different in my process. I have lot tables.
let me show you my create code and update method coding.
Create method code:
public function store(Request $request)
{
$tradeID= Auth::user()->trade()->create($input);
$input = $request->all();
$reasons = $request->input('reason');
//Loop for creating KEY as Value
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
if( $data > 0 ) {
foreach ($data as $datum) {
$tradeID->tradereason()->save(new TradeReason($datum));
}
}
}
this is my tring code for update method:
public function update(Request $request, $id)
{
$tradeID= Auth::user()->trade()->whereId($id)->first()->update($input);
$input = $request->all();
$reasons = TradeReason::whereId($id)->first();
$reasons->update($input);
$reasons->tradereason()->sync($request->input('reason'));
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
if( $data > 0 ) {
foreach ($data as $datum) {
$tradeID->tradereason()->whereId($id)->first()->update($datum);
}
}
}
update returns a boolean. So, don't overwrite $tradeID with the results of update.
$tradeID = Auth::user()->trade()->whereId($id)->first();
$tradeID->update($input);
Calling update on the Builder returns an 'int'. Calling update on the Model returns a 'bool'. They don't return Model instances.
// bool
$tradeID= Auth::user()->trade()->whereId($id)->first()->update($input);
The model instance would be what is returned from the first call:
$tradeID = Auth::user()->trade()->whereId($id)->first(); // assuming it finds a record
You can update that, you can use it in the foreach loop.

Laravel 5.1 Command empty table

I'm using a command to add products from an API to my database using the following code
class UpdateCatalog extends Command {
protected $name = 'catalog:update';
protected $description = 'Command description.';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$products = Api::productsGetProducts();
foreach($products as $product)
{
$detail = Api::productsGetProduct($product['id']);
$product = new Product();
$product->id = $detail->getId();
$product->external_id = $detail->getExternalId();
$product->name = $detail->getName();
$product->description = $detail->getDescription();
$product->thumbnail = $detail->getThumbnail();
$product->price = $detail->getPrices()[0]['price_excl_vat'];
$product->vat = $detail->getVat();
$product->save();
}
}
}
Now I'm wondering if it's possible to empty the table prior to filling it again.
Thank you!
Do you mean you want to empty your Product database table?
This can be done with truncate like this:
Product::truncate();
Note: This will remove all rows and reset the auto-incrementing ID to zero

How can I use CodeIgniter form dropdown function?

codeIgniter form_dropdown() function can receive only associative array but I have multi dimension array by using result_array() function. How can I fetch my data on form_dropdown() function?
Let's say you want a dropdown of items, using result_array():
$query = $this->db->query("SELECT id, item_name FROM items");
$options = array();
foreach ($query->result_array() as $row){
$options[$row['id']] = $row['item_name'];
}
echo form_dropdown('my_items_dropdown', $options, '1');
I have extended the class DB_result.php in system/database with this new function
public function dropdown_array($id_field = FALSE, $list_field = FALSE)
{
$result = array();
if ($id_field === FALSE || $list_field === FALSE) return $result;
$array = $this->result_array();
foreach ($array as $value) {
$result[$value[$id_field]] = $value[$list_field];
}
return $result;
}
Now you can simply call from every Model class your new function to generate a dropdown-compliant array like this:
$customers = $this->db->get('customers');
$result = $customers->dropdown_array('id', 'name');
return $result;

Getting data from model to controller

I do have a question : I cannot pass the data from model to controller
You can see some of my codes, please help me.
It does not work!
this is my model "mymodel.php"
....
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
if($query){
foreach ($query->result() as $row);
}
$t = "EXAMPLE/{$row->code}";
function wandad() {
return $t;
}
.....
and this is my controller mycont.php
...
$this->load->model('mymodel');
$data['new'] = $this->Mymodel->wandad();
$this->load->view('myview',$data);
...
and this is my view myview.php
....
echo $new;
.....
Clearly you The model is not written properly and to corrent this simple do this
1.) I put a default value on $t
2.) I put the query >> loop on the inside function
wandad
so it can be executed once called from controller
function wandad() {
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
$t = "";
if($query){
foreach ($query->result() as $row){
$t = "EXAMPLE/{$row->code}".'<br>';
}
}
return $t;
}
Here are several issues into your model
Your Foreach function doesn't do anything
$t is not in the same namespace than wandad()
Function wandad is not defined into your model class
I'm not sure of what you wanna get with wandad() function but here's a pattern.
function yourFunction()
{
/* This will return the full query as an array */
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1")->result_array();
/* Store variable in the same class */
$this->t = "EXAMPLE/".$query[0]['code'];
/* Close yourFunction() */
}
public function wandad() {
return $this->t;
}
Then into your controller, do that instead :
$this->load->model('mymodel');
$this->mymodel->yourFunction();
$data['new'] = $this->mymodel->wandad();
$this->load->view('myview',$data);
#Touki his foreach actually does something. It will set the variable $row with the last row that is returned from the query. Not the best way to do it ... But it's a way. Better would be to use a limit in the query.
There is a small mistake in your code #Ernesto.that is
foreach ($query->result() as $row){
$t. = "EXAMPLE/{$row->code}".'<br>';
}
but your code was simply nice

Resources