Laravel pass value from foreach loop in controller to view - laravel

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

Related

get all data count from relationship | 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);
}

Running same query in 2 different views: What's the proper way?

Just getting started into laravel and need to run the same db query for 2 different views, I know I could just create 2 controllers and perform the same query in both passing it to each view.
But, is that the proper way? Or is there a way without repeating my code?
Thanks!
Edit:
I have the following function inside a controller:
protected function getLocation($url)
{
$match = ['url' => $url];
$location = DB::table('location')->where($match)->first();
if (!$location) {
abort(404);
}
return $location;
}
the controller is returning that data to a view:
public function showsubcatandlocation($service)
{
$category = $this->getCat($service);
$location = $this->getLocation($category);
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);
}
What's the proper way to reuse the getLocation function? Or should I just copy it in the new controller? I just need to use it in those 2 views.
maybe scope Query helps?
class Location extends Model
{
public function scopeMatch($query, $url)
{
return $query->where('url', $url);
}
}
And then your two controllel methods will be
$location = Task::match($url)->first();
if (!$location) {
abort(404);
}
return $location;
$category = $this->getCat($service);
$location = Task::match($category['url'])->first();
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);

Laravel 5.6 Many To Many Polymorphic Relations Insert Not Work

I'm use laravel 5.6 on this project. Categories value not recorded 'categorizables' pivot table. I check with f12 or bug but I do not get any errors. all of them ok but not recorded pivot table. Where I have
been mistake.
My Blog project sql structure is below
--blogs
id
title
description
...
-- categorizables
category_id
categorizable_id
categorizable_type
Below code belong to Category.php Model
class Category extends Model
{
protected $primaryKey='category_id';
public function blogs(){
return $this->morphedByMany('App\Blog', 'categorizable', 'categorizables', 'category_id');
}
}
Above code belong to Blog.php
public function category($categories)
{
$categories = Blog::buildCatArray($categories);
foreach ($categories as $catName) {
$this->addOneCat($catName);
$this->load('categories');
}
return $this;
}
public function buildCatArray($categories): array
{
if (is_array($categories)) {
$array = $categories;
} elseif ($categories instanceof BaseCollection) {
$array = $this->buildCatArray($categories->all());
} elseif (is_string($categories)) {
$array = preg_split(
'#[' . preg_quote(',;', '#') . ']#',
$categories,
null,
PREG_SPLIT_NO_EMPTY
);
} else {
throw new \ErrorException(
__CLASS__ . '::' . __METHOD__ . ' expects parameter 1 to be string, array or Collection; ' .
gettype($categories) . ' given'
);
}
return array_filter(
array_map('trim', $array)
);
}
protected function addOneCat(string $catName)
{
$cat = Self::findOrCreate($catName);
$catKey = $cat->getKey();
if (!$this->cats->contains($catKey)) {
$this->categories()->attach($catKey);
}
}
public function find(string $catName)
{
return $this->Category::$catName->first();
}
public function findOrCreate(string $catName): Category
{
$cat = $this->find($catName);
if (!$cat) {
$cat = $this->Category::create(['name' => $catName]);
}
return $cat;
}
This my Blog Controller file store class
BlogController.php
public function store(Request $request)
{
$data = new Blog;
$data->title = $request->title;
$data->content = $request->content;
$tags = explode(',',$request->tag);
$categories = explode(',',$request->category);
$data->save();
$data->tag($tags);
$data->category($categories);
}
Best wishes

Codeigniter function_exists not working correctly

I am using php function_exists() function exist on my Welcome controller. But for some reason it keeps on throwing my show_error even though my slideshow function exists.
With in my foreach loop I get module function name from database which in the foreach loop is called $function = $module['code'];
Question is: How am I able to make sure function_exists checks
function exists correctly?
<?php
class Welcome extends CI_Controller {
public function index() {
$data['content_top'] = $this->content_top();
$this->load->view('home', $data);
}
public function content_top() {
$data['modules'] = array();
$modules = $this->get_module();
foreach ($modules as $module) {
$function = $module['code'];
if (function_exists($function)) {
$setting_info = array('test' => 'testing');
if ($setting_info) {
$data['modules'][] = $this->$function($setting_info);
}
} else {
show_error('This ' . $function . ' does not exist on ' . __CLASS__ . ' controller!');
}
}
return $this->load->view('content_top', $data, TRUE);
}
public function banner() {
}
public function slideshow($setting) {
$data['test'] = $setting['test'];
$this->load->view('module/slideshow', $data);
}
public function get_module() {
$query = $this->db->get('modules');
return $query->result_array();
}
}
function_exists() works on functions, but not class methods - these are different things. What you want is method_exists():
method_exists($this, $function);

Laravel Passing Variable from a controller to another Controller

I'm trying to pass a variable from a controller to another controller I tried using
Redirect::to('dashboard/'.$ssid.'/')->with(compact('wname'))
but does not work any idea how can I achieve this?
here is my code
Route
Route::get('dashboard/{ssid}/', 'HomeController#showDash');
LoginController
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value):
$activated = $value['a_status'];
$wname = $value['wholename'];
endforeach;
if($activated == 1):
$red= Redirect::to('dashboard/'.$ssid.'/')->with(compact('wholename'));
else:
$red= View::make('login');
endif;
return $red;
}
}
HomeController
public function showDash($ssid,$wholename)
{
foreach ($wholename as $userVal):
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
endforeach;
return View::make('dashboard')->with(compact('fn'));
}
The error I'm having is that Missing argument 2 for HomeController::showDash() as per laravel's debugger..
Updated answer based on the comments:
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value){
$activated = $value['a_status'];
$wname = $value['wholename'];
}
if($activated == 1) {
Redirect::to('dashboard/'.$ssid.'/')->with(['wholename' => $wholename]);
}
return View::make('login');
}
public function showDash($ssid)
{
$wholename = (Session::has('wholename')) ? Session::get('wholename') : [];
foreach ($wholename as $userVal) {
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
}
return View::make('dashboard')->with(compact('fn'));
}
Everything else can stay as is.
Update: fixed erroneous space in 'whole name' (autocorrect did that, sorry).

Resources