How to get data from database without looping? - laravel

In my controller function there is a foreach loop having query builder to get data from the database and after ending foreach loop, data is passed into views. This is looping more than 90 times.
class HomeController extends Controller {
public $menu;
public $msg;
public function __construct() {
$this->isEditor();
$this->menu = Config::get('constants.news.menu');
$this->msg = Config::get('constants.news');
}
public function index(Request $request) {
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
//dd(session()->all());
$sessval = session()->all();
$uroles = DB::table('users_roles')
->where('id', Auth::user()->id)
->where('role_id','4')
//->toSql();
->get();
foreach($uroles as $key => $value)
{
$urole[]=$value->col-name;
$companiesid[]=$value->col-name2;
$rpending=DB::table('')
->select('')
->where('')
->where('')
->whereRaw("")
->count();
$abc+=$rpending;
$cactivities=DB::table('')
->select('')
->where('','=','')
->where('','=',$value->)
->where('','=',$value->)
->count();
$def+=$cactivities;
$pactivities=DB::table('')
->select('')
->where('','=','0')
->where('','=',$value->)
->where('','=',$value->)
->count();
$mno+=$pactivities;
$uactivities=DB::table('')
->select('')
->where('','=','0')
->where('','=',$value->)
->where('','=',$value->)
->whereBetween('due_date', [$tfrom, $to])
->count();
$ghi+=$uactivities;
$delayed=DB::table('')
->select('')
->where('','=','1')
->where('','=',$value->)
->where('','=',$value->)
->whereRaw('`actual_date`>`due_date` ')
//->toSql();
->count();
$jkl+=$delayed;
}
return view('view.name', compact('abc', 'def', 'ghi', 'jkl', 'mno'));
}
Any possible way to fetching the data in the background and when user loggedin it will render the view faster. Also i need to pass more data to the same view and that data is also getting from the database using forloop. How to reduce the loading time?. Please suggest any alternative way.
In view-
<div class="row">
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-green" style="background:green !important">
<div class="inner">
<h3>{{ $abc}}</h3>
<p>Comp</p>
</div>
<div class="icon">
<i class="fa fa-thumbs-up"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-orange" style="background: darkorange !important">
<div class="inner">
<h3>{{ $def}}</h3>
<p>Delayed</p>
</div>
<div class="icon">
<i class="fa fa-book"></i>
</div>
<a href="#" class="small-box-footer">More info <i class="fa fa-
arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-red"style="background: red !important">
<div class="inner">
<h3>{{ $ghi}}</h3>
<p>Pen</p>
</div>
<div class="icon">
<i class="fa fa-clock-o"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-aqua">
<div class="inner">
<h3>{{ $jkl}}</h3>
<p>Pending</p>
</div>
<div class="icon">
<i class="fa fa-user-plus"></i>
</div>
<a href="#" class="small-box-footer">More info <i class="fa fa-
arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
</div>

The issue here is with inefficient database queries. Querying within a loop usually results in poor performance.
A better approach would be to fetch all related data to user roles using SQL Joins or Eloquent Relationships.

Related

Property [Total_Sayur] does not exist on this collection instance

how to display or call value in array in laravel blade view ?
I already have the data that appears in the image below:
enter image description here
I still don't understand how to call the data in the :
<h3>#currency($laporan->Total_Sayur)</h3>
I'm tired of trying it in various ways and it always appears another error message. Please help me
MyController
public function index()
{
$users = User::count();
$kelompok = Kelompok::count();
$anggota = Anggota::count();
$laporan = Anggota::select('kecamatan', Produk::raw('avg(total_sayur) as Total_Sayur, avg(total_buah) as Total_Buah,avg(total_ikan) as Total_Ikan, avg(total_ternak) as Total_Ternak'))
->leftjoin('produk', 'produk.anggota_id', '=', 'anggota.id')
->where('kecamatan', '=', 'Ngajum')
->GroupBy('kecamatan')
->get();
// return $laporan;
return view('Dashboard.index', compact('users', 'kelompok', 'anggota', 'laporan'));
}
View
<div class="row">
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-info">
<div class="inner">
<h3>#currency($laporan->Total_Sayur)</h3>
<p>TOTAl KEMANFAATAN</p>
</div>
<div class="icon">
<i class="ion ion-pricetagg"></i>
</div>
More info <i class="fas fa-arrow-circle-right"></i>
</div>
</div>
</div>
Your solution start from here....
<div class="row">
<div class="col-lg-3 col-6">
#foreach($laporan as $item)
<!-- small box -->
<div class="small-box bg-info">
<div class="inner">
<h3>#currency($item->Total_Sayur)</h3>
<p>TOTAl KEMANFAATAN</p>
</div>
<div class="icon">
<i class="ion ion-pricetagg"></i>
</div>
More info <i class="fas fa-arrow-circle-right"></i>
</div>
#endforeach
</div>
</div>

I want to show assigned users using laravel

I am trying to show assigned users to the user I have made relationship b/w user and user_permission but I am facing an error.how to fix it thanks. please check this error https://flareapp.io/share/q5Y12O5X#F52 Can anyone provide me a solution that where I am wrong.
Database table
user_permission table
please see here https://ibb.co/7486n95
user table
please see here https://ibb.co/5jmqb0H
Controller
public function index()
{
$users=User::with('permission')->where('id' ,'!=' ,Auth::id())->paginate(6);
return view('index',compact('users'));
}
User Model
class User extends Authenticatable
{
public function permission()
{
return $this-
>hasMany('App\Users_permissions','user_Access_id','id');
}
}
Users_permissions Model
class Users_permissions extends Model
{
protected $table = 'user_permission';
protected $fillable = ['id','user_id', 'user_Access_id'];
public function user()
{
return $this->belongsTo('App\User','id');
}
}
Html View
<!-- Default box -->
<div class="card card-solid">
<div class="card-body pb-0">
<div class="row d-flex align-items-stretch">
#foreach($users->permission as $user)
<div class="col-12 col-sm-6 col-md-4 ">
<div class="card bg-light">
<div class="card-header text-muted border-bottom-0">
<div class="card-tools"> <span data-toggle="tooltip" title="3 New Messages"
class="badge badge-primary"></span>
</div>
</div>
<div class="card-body pt-0">
<div class="row">
<div class="col-7">
<h2 class="lead"><b>{{$user->name}}</b></h2>
<p class="text-muted text-sm"><b>Job: </b> {{$user->job}}</p>
<ul class="ml-4 mb-0 fa-ul text-muted">
<li class="small"><span class="fa-li"><i class="fas fa-lg fa-phone"></i></span> Phone
#: {{$user->phone_number}}</li>
</ul>
</div>
<div class="col-5 text-center">
<img src="{{url('public/assets/dist/img/user1-128x128.jpg')}}" alt="" class="img-
circle img-fluid">
</div>
</div>
</div>
<div class="card-footer">
<div class="text-left">
#if($user->isOnline())
<i class="fa fa-circle text-success"></i> Online#else
<i class="fa fa-circle text-default"></i> offline#endif</div>
<div class="text-right">
<a href="{{url('/chat',$user->id)}}" class="btn btn-sm bg-teal"> <i class="fas fa-
comments"></i><b> Chat</b>
</a>
</div>
</div>
</div>
</div>#endforeach</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<nav aria-label="Contacts Page Navigation">
<ul style="list-style-type:none;">
<li>{{$users->links()}}</li>
</ul>
</nav>
</div>
<!-- /.card-footer -->
</div>
<!-- /.card -->
Here, what you are trying to do this is you are directly accessing permission relationship from collection, this is why it is showing error. First you have to loop through users and inside that particular user permission relationship exist. So you have to loop through users model first.
Hope this helps:)
You are applying permissions to the collection of users, but only an individual user has permissions. You need to loop through all of your users, then access the users permissions:
#foreach($users as $user)
...
#foreach($user->permission as $permission)
{{$permission->name}}
#endforeach
#endforeach

Laravel Error: Too few arguments to function, 0 passed and exactly 1 expected

Using Laravel-5.8, I have this code:
public function manager_employee_list(Request $request)
{
$employees = HrEmployee::paginate(6);
return view('appraisal.appraisal_goals.manager_employee_list')->with('employees', $employees);
}
And it render this view: manager_employee_list
<div class="row d-flex align-items-stretch">
#if (count($employees))
#foreach($employees as $key => $employee)
<div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
<div class="card bg-light">
<div class="card-header text-muted border-bottom-0">
{{isset($employee->designation) ? $employee->designation->designation_name : ''}}
</div>
<div class="card-body pt-0">
<div class="row">
<div class="col-7">
<h2 class="lead"><b>Staff ID: {{$employee->employee_code}}</b></h2>
<h2 class="lead"><b>{{$employee->first_name}} {{$employee->last_name}}</b></h2>
<h6 class="lead"><b>Employee Department: </b>{{isset($employee->department) ? $employee->department->dept_name : ''}}</h6>
</div>
<div class="col-5 text-center">
#if($employee->emp_image != '')
<img src="{{ URL::to('/') }}/public/storage/employees/image/{{ $employee->emp_image }}" class="img-circle img-fluid" />
#else
<img class="profile-user-img img-fluid img-circle" src="{{asset('theme/adminlte3/dist/img/default.png')}}" alt="" class="img-circle img-fluid">
#endif
</div>
</div>
</div>
<div class="card-footer">
<div class="text-right">
<a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
<i class="fas fa-user"></i> View Goal
</a>
</div>
</div>
</div>
</div>
#endforeach
#else
<h4 style="text-align:center;">No matching records found</h4>
#endif
</div>
I want to pass the parameter
['id'=>$employee->id]
from above to another controller action:
public function manager_employee_goal($id)
{
$goals = AppraisalGoal::where('employee_id', $id)->get();
return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals);
}
It utilizes it here:
$goals = AppraisalGoal::where('employee_id', $id)->get();
When I clicked on
<a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
<i class="fas fa-user"></i> View Goal
</a>
I got this error:
Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal(), 0 passed and exactly 1 expected
and this is underlined:
public function manager_employee_goal($id)
route/web.php
Route::get('appraisal_goals/manager_employee_list', 'Appraisal\AppraisalGoalsController#manager_employee_list')->name('appraisal.appraisal_goals.manager_employee_list');
Route::get('appraisal_goals/manager_employee_goal', 'Appraisal\AppraisalGoalsController#manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
How do I resolve it?
Thank you.
You need to change in your web.php file. add {id} in URL.
otherwise, all are fine as now your get method will be like 'appraisal_goals/manager_employee_goal/{id}'
Route::get('appraisal_goals/manager_employee_goal/{id}','Appraisal\AppraisalGoalsController#manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
I believe your route need to be updated to
Route::get('appraisal_goals/manager_employee_goal/{id}','Appraisal\AppraisalGoalsController#manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');

Dynamic Bootstrap Tabs In Laravel 6

I have two tables , categories and articles.Each category has id and name. Each articles has id, name and category id. Now I want to load the data on each tab when a user click on specific category_id.so related product will be shown on each category tab. I have tried but couldn't get the solution.
Category Model
public function articles()
{
return $this->belongsToMany('App\Article')->withTimestamps();
}
Article Model
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
Controller
public function index(){
$categories = Category::with('articles')->whereIn('id', [1, 2, 3])->get();
return view('welcome',compact( 'categories'));
}
Here is the view :
<nav>
<div class="nav nav-tabs" id="nav-tab" role="tablist">
#foreach($categories as $category)
<a class="nav-item nav-link " id="nav-home-tab-{{$category->id}}" data-toggle="tab" href="#nav-home-{{$category->id}}" role="tab" aria-controls="nav-home" aria-selected="true">{{$category->title}}</a>
#endforeach
</div>
</nav>
#foreach($categories as $category)
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-home-{{$category->id}}" role="tabpanel" aria-labelledby="nav-home-tab-{{$category->id}}">
<div class="row clearfix">
#foreach($category->articles as $article)
<div class="col-md-3">
<div class="box mt-2 mb-2">
<img src="{{ $article->images ['thumb'] }}">
</div>
</div>
#endforeach
</div>
</div>
</div>
#endforeach
<nav>
<div class="nav nav-tabs" id="nav-tab" role="tablist">
#foreach($categories as $count => $category)
<a id="nav-home-tab-{{$category->id}}" data-toggle="tab" href="#nav-home-{{$category->id}}" role="tab" aria-controls="nav-home" aria-selected="true"
#if($count == 0) class="nav-item nav-link active" #else()class="nav-item nav-link "#endif>{{$category->title}}</a>
#endforeach
</div>
</nav>
<div class="tab-content" id="nav-tabContent">
#foreach($categories as $count => $category)
<div #if($count == 0) class="tab-pane fade show active" #else class="tab-pane fade" #endif id="nav-home-{{$category->id}}"
role="tabpanel" aria-labelledby="nav-home-tab-{{$category->id}}">
<div class="row ">
#foreach($category->articles as $article)
<div class="col-md-3">
<div class="box mt-2 mb-2">
<img src="{{ $article->images ['thumb'] }}">
<h2>قالب بوتسراپ شرکتی</h2>
<p>قالب بوت استراپ شرکتی کاملا فارسی سازی شده و رایگان میتوانید دانلود کنید</p>
<div class=" download-btn">
<i class="fa fa-download"></i> دانلود قالب
<i class="fa fa-laptop"></i> دموی قالب
</div>
</div>
</div>
#endforeach
</div>
</div>
#endforeach
</div>

Undefined variable: product in blade view

<div class="row">
#foreach($product as $data)
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img src="{{ asset('image/product_image/'.$data->product_image) }}" alt="photo">
<div class="card-body">
<h4 class="card-title">
{{ $data->product_name }}
</h4>
<h5>{{ $data->product_price }}</h5>
<p class="card-text">{{ $data->product_description }}</p>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
#endforeach
<!-- /.row -->
</div>
First collect what you want in the controller. It could be something like this:
$product = Product::all();
And then you must send the product variable to the view. Something like this:
return view('path.to.view', compact('product'));
By the way. it's better to use plural form products.
You can add the code in the blade to retrieve all the products from the product model
<div class="row">
#php
$product = App\Product::all();
#endphp
#foreach($product as $data)
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img src="{{ asset('image/product_image/'.$data->product_image) }}" alt="photo">
<div class="card-body">
<h4 class="card-title">
{{ $data->product_name }}
</h4>
<h5>{{ $data->product_price }}</h5>
<p class="card-text">{{ $data->product_description }}</p>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
#endforeach
<!-- /.row -->
</div>
Your code should be like this
Controller's index method,
public function index()
{
$product = Product::all();
return view('path', compact('product'));
}

Resources