In my database I have many to many relation between notifications and statuses table. So the pivot table stored the notification_id, statuses_id and values. Now, in my model I wrote a function historysStatus, which extracts that values and created_at from pivot table
public function historystatus()
{
$o_status = Status::where('name','health')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values','created_at')->first();
if($o_response === null){
return false;
}
return ['value' => $o_response->values,
'timestamp' => $o_response->created_at];
}
I want to iterate through all the values and timestamps associated with a specific notification.thus in blade I wrote the for each loop to iterate through all values and created at.
#foreach($notes as $notification)
<?php $notificationHealth = $notes->historystatus('health'); ?>
<tr>
<td>{{ $notificationHealth['timestamp'] }}</td>
<td> {{ $notificationHealth['value'] }}</td>.
</tr>
#endforeach
</tbody>
instead it gave me only the last record 4 times. Is something wrong with the sql query? I would appreciate any suggestion and ideas?
Inside the foreach try using $notification->historystatus('health'); instead of $notes->historystatus('health');
#foreach($notes as $notification)
<?php $notificationHealth = $notification->historystatus('health'); ?>
<tr>
<td>{{ $notificationHealth['timestamp'] }}</td>
<td> {{ $notificationHealth['value'] }}</td>.
</tr>
#endforeach
public function history($s_type)
{
if (!in_array($s_type, ['speed', 'health'])){
return false;
}
$o_status = Status::where('name', strval($s_type))->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values', 'created_at')->orderBy('created_at','DESC')->get();
if($o_response === null || $o_response->count() === 0){
return false;
}
$a_ret = [];
foreach ($o_response as $o_status) {
$a_ret[] = [
'value' => $o_status->values,
'timestamp' => $o_status->created_at
];
}
return $a_ret;
}
this is the simple answer i figured out. and the foreach loop in side the blade.
Related
I want to ask if ever I can limit my data in table. I want to remove one data out of my 6 data.
here is my table
Now I want to remove number 3 row which is SESSION_VALIDITY how can I remove that data and make it just 5 data in my table? I want to limit my data coz' I dont need to view SESSION_VALIDITY. help thanks
my Index
#foreach ($settings as $setting)
<tr>
<td>{{ $setting->settings_code }}</td>
<td>{{ $setting->subject}}</td>
<td>{{ $setting->description }}</td>
<td></td>
</tr>
#endforeach
my Controller
public function index()
{
$settings = Setting::all();
return view('admin.settings.index', compact('settings'));
}
If you just want to not show that row in your $settings data, you can exclude it using your query like this.
public function index()
{
$settings = Setting::where('settings_code', '<>', 'SESSION_VALIDITY')->get();
return view('admin.settings.index', compact('settings'));
}
If you want to delete it entirely, you can run a one-time function to delete that row from the table.
public function deleteSessionValidity()
{
$setting = Setting::where('settings_code', 'SESSION_VALIDITY')->first();
$setting->delete();
}
You should filter your query in the controller.
Instead of Setting::all(), you should use:
$settings = Setting::where('settings_code', '!=', 'SESSION_VALIDITY')->get();
You should try this:
public function index()
{
$settings = Setting::where('settings_code', '!=', 'SESSION_VALIDITY')->get();
return view('admin.settings.index', compact('settings'));
}
OR
#foreach ($settings as $setting)
<tr>
#if($setting->settings_code != "SESSION_VALIDITY")
<td>{{ $setting->settings_code }}</td>
<td>{{ $setting->subject}}</td>
<td>{{ $setting->description }}</td>
<td></td>
#endif
</tr>
#endforeach
inside foreach put if statement
like:
#foreach ($settings as $setting)
#if ($setting->settings_code != "SESSION_VALIDITY")
your <td> here
#endif
#endforeach
this is not duplicate but related to the topic Query inside for loop in laravel
Is this the correct code in laravel for putting query inside the loop
//controller
public function dtrdata()
{
for($i=1;$i<=$totalnumdays;$i++){
$query= DB::table('dtrrecords')
->where('dtrrecords.bio_id', $i)
}
return view('pages/admin.dtrdata', compact('query','i'));
}
//view
#foreach($query as $row => $rows1)
<tr>
<td>{{$rows1->AM_IN}}</td>
</tr>
#endforeach
There are a couple problems with your loop. First you are overwriting the $query variable on each iteration. Second, you need to call ->get() to execute the query and return results. The following illustrates how to add multiple query results into a single collection and then loop the results in the view:
public function dtrdata()
{
$collection = collect();
for($i=1;$i<=$totalnumdays;$i++){
$records = DB::table('dtrrecords')->where('dtrrecords.bio_id', $i)->get();
$collection->concat($records)
}
return view('pages/admin.dtrdata', compact('collection'));
}
#foreach($collection as $item)
<tr>
<td>{{ $item->AM_IN} }</td>
</tr>
#endforeach
You can do your job by another solution without looping:
public function dtrdata()
{
// Make an array from 1 to $totalnumdays using php range function
// follow the link for range function https://www.w3schools.com/php/func_array_range.asp
$numDays = range(1,$totalnumdays);
$query= DB::table('dtrrecords')
->whereIn('dtrrecords.bio_id', $numDays) // Use laravel whereIn method
->get();
return view('pages/admin.dtrdata', compact('query'));
}
//view
#foreach($query as $row => $rows1)
<tr>
<td>{{$rows1->AM_IN}}</td>
</tr>
#endforeach
I have several row in a table in db and every row related with three tables and every table has many rows. when i loop main table rows i also loop three tables rows now if one of tables has a content in row then i want to prevent showing entire sub that loop only which contain a value.
In my controller:
public function classWiseResult(Request $request){
$students = Students::where('class',$request->class)
->with('firstTerm')
->with('secondTerm')
->with('finalTerm')
->get();
return view('admin.showResult.show',compact('students'));
}
in my view:
#foreach($students as $student)
<tr>
<td>{{$student->id}}</td>
<td>{{$student->fname}}</td>
<?php $Ftotal = 0; $Fcount = 0; ?>
#foreach($student->firstTerm as $first)
<?php $Fcount++;?>
<?php $Ftotal += gradePoint($first->number); ?>
#endforeach
<?php $fttp = gpa($Ftotal, $Fcount) ;?>
<td>{{$fttp}}</td>
<td>
#if($Ftotal){
{letterGrade(gpa($Ftotal, $Fcount))}
}
#endif
</td>
Result:
I want to skip showing result if I have a subject number under 32
This method uses relationship count comparison.
Controller
public function classWiseResult(Request $request){
$students = Students::where('class',$request->class)
->withCount(['firstTerm as firstTermPromoted' => function($q) {
$q->where('number', '>', 32);
}])
->withCount('firstTerm as firstTermAllCount')
->withCount(['secondTerm as secondTermPromoted' => function($q) {
$q->where('number', '>', 32);
}])
->withCount('secondTerm as secondTermAllCount')
->withCount(['finalTerm as finalTermPromoted' => function($q) {
$q->where('number', '>', 32);
}])
->withCount('finalTerm as finalTermAllCount')
->with('firstTerm')
->with('secondTerm')
->with('finalTerm')
->get();
return view('admin.showResult.show',compact('students'));
}
In your view you can compare the total count of all relations and count of relations that passes the condition.
View
#foreach($students as $student)
#if($student->firstTermPromoted == $student->firstTermAllCount
&& $student->secondTermPromoted == $student->secondTermAllCount
&& $student->finalTermPromoted == $student->finalTermAllCount)
{{ "Promoted" }}
#else
{{ "Not Promoted" }}
#endif
#endforeach
As I am developing a project in larawel 5.3. and I am using two tables in database first users ans second points you can see my points table structure in this link.
I want to get user id in laravel 5.3 controller with Auth::user()->id but it creates error their
So when a transection occurs. it is saved in points table getting assousiated with user_id so net points of a user can can be taken as using folloing query
$points = Points::select(DB::raw("sum(p_add)-sum(p_less) as Total"))->where('user_id', Auth::user()->id)->first();
now I am goin to gett all data of users in a single admin page. so I am using following code in controller
public function users_list()
{
$ptitle = "Website Users";
$pdesc = "";
$total_users = User::count();
$users = User::select('*')->orderby('created_at', 'desc')->get();
return view('admin.all-users-list',
['ptitle' => $ptitle,
'pdesc' => $pdesc,
'users' => $users,
'total_users' => $total_users,
]);
}
And folloing foreach loop to fetch users data in view page
<table class="table table-hover">
<tbody><tr>
<th>ID</th>
<th>User Name</th>
<th>Email</th>
<th>Country</th>
<th>Date</th>
<th>Points</th>
</tr>
<?php foreach ( $users as $u ){ ?>
<tr>
<td>{{ $u->id }}</td>
<td>{{ $u->user_name }}</td>
<td>{{ $u->email }}</td>
<td>{{ $u->country }}</td>
<td>{{ $u->created_at }}</td>
<td>????</td>
</tr>
<?php }?>
</tbody></table>
and result on view is as in this image
now I dont now that how can I fetch net points from points table for every user. please provide me some help to solve this issue.
you can make public function and call it every loop in foreach loop. Or create static function on the Points model class to get points for every user by using user_id as argument.
Put getUserPoints on Points model class
public static function getUserPoints($userId){
$points = self::select(DB::raw("sum(p_add)-sum(p_less) as Total"))
->where('user_id', $userId)->first();
if( $points != null ){
return $points->Total;
}
return 0;
}
}
And you can call it every loop as {{ \App\Points::getUserPoints($u->id) }}
I am building a simple voting application in Laravel 4 where candidates are being voted for. I have two entities Candidate and Vote with a one to many relationship. When someone clicks on a button, I get the id of the candidate and store it in the vote table with only one field of candidate_id. I have a VoteController function called votesuccess that looks like this
$vote = new Vote;
$candidate_id =Input::get('name');
$candidate = Candidate::find($candidate_id);
$vote = $candidate->votes()->save($vote);
$count = DB::table('votes')->where('candidate_id','==','$candidate_id')->count();
Session::flash('message', 'Successfully Cast your vote!');
return Redirect::to('voteresults')->with('count',$count);
From the above I have another VoteController function called voteresults which I pass in all the candidates like so
$candidates = Candidate::all();
return View::make('votes.voteresults',['candidates'=>$candidates]);
Am storing the votes as rows and I want to count the votes by counting the rows hence this code
$count = DB::table('votes')->where('candidate_id','==','$candidate_id')->count();
am attempting to access all the candidate information plus the number of votes they have got from a view called voteresults which looks like this
<tbody>
#foreach($candidates as $key => $value)
<tr>
<td><img src="{{$value->avatar->url('thumb')}}" alt="..."></td>
<td>{{ $value->name }}</td>
<td>{{ $value->manifesto }}</td>
<td>
{{ $count }}
</td>
</tr>
#endforeach
</tbody>
Am attempting to pass the $count variable to the view so that I can capture the number of votes for a candidate. I don't know if it can be done this way or there is a better way to do it.When I try to run this I get undefined variable count Any guidance is welcome.
If i get you correctly you want to pass two different things (candidates and votes) from your controller to your view?
Controller:
$candidates = Candidate::all();
$count = DB::table('votes')->where('candidate_id','=','$candidate_id')->count();
return View::make('votes.voteresults')->with('candidates', $candidates)->with('count',$count);
View:
<tbody>
#foreach($candidates as $key => $value)
<tr>
<td><img src="{{$value->avatar->url('thumb')}}" alt="..."></td>
<td>{{ $value->name }}</td>
<td>{{ $value->manifesto }}</td>
<td>
{{ $count }}
</td>
</tr>
#endforeach
</tbody>
See this documentation:
Views
I believe one issue you have is that within your where criteria for $count query you have your $candidate_id variable within single quotes. I didn’t test, but try the code below.
$vote = new Vote;
$candidate_id =Input::get('name');
$candidate = Candidate::find($candidate_id);
$vote = $candidate->votes()->save($vote);
Session::flash('message', 'Successfully Cast your vote!');
return Redirect::to('voteresults');
Add a method to Candidate model similar to this:
public function getTotalVotesAttribute()
{
return $this->hasMany('Vote')->whereCandidateId($this->id)->count();
}
In your VoteResults controller:
$candidates = Candidate::all();
return View::make('votes.voteresults',['candidates'=>$candidates]);
In your voteresults view:
<tbody>
#foreach($candidates as $key => $value)
<tr>
<td><img src="{{$value->avatar->url('thumb')}}" alt="..."></td>
<td>{{ $value->name }}</td>
<td>{{ $value->manifesto }}</td>
<td>
{{ $value->total_votes }}
</td>
</tr>
#endforeach
</tbody>