i tried so hard to change the value inside collection and nothings was happen
here is my footage of datatable in html
i want to change that value of 0 and 1 into 'active' and 'non-active'
i tried change it on my function controller and didn't work
controller.php
public function reportView()
{
$data = ReportViewAll::paginate(5);
$reportviewall = $data->map(function($item, $key){
$key = 'crewprogram_isdisabled';
($item = 0) ? $item = 'active' : $item = 'non-active';
return $item;
});
return view('CrewProgram.ReportView.index', compact('reportviewall'));
}
how do i solve that?
and instead change it in function, can i change it in Eloquent model?
Eloquent Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ReportViewAll extends Model
{
protected $connection = 'sqlsrv2';
protected $table ='view_mastercrewprogram';
}
How can i solve this?
EDIT
this is my table, i tried some stuff up in my blade and still not working
table.blade.php
<tbody>
#foreach($reportviewall as $mastercrew)
<tr>
<td class="nik">{{$mastercrew->employee_nik}}</td>
<td class="nik">{{$mastercrew->employee_nama}}</td>
<td class="nik">{{$mastercrew->crewprogramposition_name}}</td>
<td class="nik">{{$mastercrew->show_focus_id}}</td>
<td class="nik">{{$mastercrew->show_name}}</td>
<td class="nik">{{$mastercrew->crewprogrammemo_placement_id}}</td>
<td class="nik">{{ \Carbon\Carbon::parse($mastercrew->crewprogrammemo_placement_date)->format(' d-m-Y ')}}</td>
<td class="nik">{{
($mastercrew->crewprogram_isdisabled = '0') ? $mastercrew->crewprogram_isdisabled = 'active' : $mastercrew->crewprogram_isdisabled = 'non-active'
}}</td>
<td class="nik">{{$mastercrew->crewprogrammemo_dismissal_id}}</td>
<td class="nik">{{ \Carbon\Carbon::parse($mastercrew->crewprogrammemo_dismissal_date)->format(' d-m-Y ')}}</td>
</tr>
#endforeach
</tbody>
So I know you have solved your issue in your code by swapping the = for a correct comparison == so that you show active/non-active as asked. However, I would like to show you a few different ways of acheiving the same outcome but with better readability.
Option 1: Zero is falsey
I assume your table.blade.php field now looks like this:
<td class="nik">{{
($mastercrew->crewprogram_isdisabled == '0') ? $mastercrew->crewprogram_isdisabled = 'active' : $mastercrew->crewprogram_isdisabled = 'non-active'
}}</td>
This can be refactored to the below and you should get the same result.
<td class="nik">{{$mastercrew->crewprogram_isdisabled ? 'non-active' : 'active'}}</td>
Just as a reference the correct word is inactive when something is not active.
Option 2: Add a mutator method to your model
Laravel has lots of additional features you can do on your models to help when using them in your blade views. One of these is called mutators (see docs: https://laravel.com/docs/7.x/eloquent-mutators#introduction).
This basically lets you add additional fields to your models to prevent adding unnecessary logic to your blade views. I recommend doing this if you plan to display active/non-active in other places as well.
So you could add this function to your ReporyViewAll model:
public function getActiveStatusAttribute()
{
return $this->crewprogram_isdisabled ? 'non-active' : 'active';
}
Then in your table.blade.php you can change the field to this:
<td class="nik">{{$mastercrew->active_status}}</td>
to solve the problem its just use '==' instead '=', maybe i need to sleep
Related
im trying to get the latest data on database, im using this on my views :
#foreach ($shows as $s)
<tbody>
<tr>
<th scope="row">{{$loop->iteration}}</th>
<td>{{$s->nama}}</td>
<td>{{$s->umur}}</td>
<td>{{$s->alamat}}</td>
<td>{{$s->nama_ortu}}</td>
<td>{{$s->posyandu}}</td>
<td>{{$s->result}}</td>
</tr>
</tbody>
#endforeach
and on controller :
public function showresultpasien()
{
$shows = DB::table('pasiens')->orderBy('id', 'DESC')->first();
return view('result', compact('shows'));
}
did i doin something wrong ?
The name of the function in the model cannot be the same as the name of a field in your table. Also in my case the column names do not follow the laravel/eloquent nomenclature so another parameter is added to belongsTo with the field name
I am having issues understanding the "belongsTo" method in a class I am working with.
I have an "Asset" model which wasn't written by me, but I'd guess it works, and it has this function where I am trying to access the 'name' property of the "AssetMake" table (Which foreign and primary key args look about right):
public function assetMake()
{
return $this->belongsTo(AssetMake::class, 'assetmake_id', 'id');
}
In a blade template that looks something like this, with the $asset variable injected in (and succesfuly already being used on the same page):
#foreach($assets as $asset)
<tr>
<td width="5%" class="filter_id">{{ $asset['unit_id'] }}</td>
<td width="20%" class="filter_type">{{ $asset['TypeName'] }}</td>
<td width="25%">{{ $asset['description'] }}</td>
<td width="20%">{{ $asset->assetMake()->get() }}</td>
</tr>
#endforeach
"AssetMake" looks like this, do I need a corresponding "hasMany" function?:
class AssetMake extends Model
{
use ModelDateSerializeNonISO;
protected $table = 'assetmake';
protected $primaryKey = 'id';
protected $hidden = ['updated', 'created'];
}
I have tried acessing the injected $asset variable in a blade template as such:
<td width="20%">{{ $asset->assetMake->get }}</td>
<td width="20%">{{ $asset->assetMake->get() }}</td>
<td width="20%">{{ $asset->assetMake()->get }}</td>
<td width="20%">{{ $asset->assetMake->name }}</td>
<td width="20%">{{ $asset->assetMake()->name }}</td>
The 'name' property of the assetmake table is what I really need access to here.
Is this some kind of lazy/eager loading problem? I'm just not sure exactly what's happening here, and why I can't access the property. I've checked in various sources, and nothing I've tried works, but I'm sure it's fairly straight forward. Any tips?
The way to access a related model is to call it as you would normally call a property. So something like $asset->assetMake->name should work.
Behind the scenes, I believe Laravel uses PHP's magic methods to create properties on the model based on the method names so that they point to the related model (parent or child).
Similarly, if you have a hasMany relationship like so:
public function children()
{
return $this->hasMany(Child::class, 'child_id',);
}
You can access the children just by calling $parent->children.
And if you need to access the Child query builder from the parent, you have to call the children() method.
E.g
$parent->children()->create($childData)
Ok, I worked it out. It was an issue with the controller. I'm still working this out and the magic in Laravel can be confusing to me. I added the line "->join('assetmake', 'assetmake.id', 'asset.assetmake_id')" to the controller query. And added to the select statement as well 'assetmake.name as AssetMakeName'
$assets = FleetFuel::where('fleet_fuel.customer_id', $user->customer_id)
->where('fleet_fuel.isOrphan', 0)
->where('fleet_fuel.hours', '>=', 0) // -1.00 = first ever record
->where('fleet_fuel.burn', '>=', 0) // -1.00 = first ever record
->join('asset', function($join) {
$join->on('fleet_fuel.unit_id', '=', 'asset.Unit_ID');
$join->on('fleet_fuel.customer_id', '=', 'asset.Customer_ID');
})
->join('assettype', 'assettype.ID', 'asset.assettype_id')
->join('assetmake', 'assetmake.id', 'asset.assetmake_id')
->select('fleet_fuel.unit_id', DB::raw('max(fleet_fuel.delivery) as lastfuel'), 'asset.description', 'asset.Rego', 'assettype.Name as TypeName', 'assetmake.name as AssetMakeName')
->groupBy('fleet_fuel.unit_id')->get();
return view('fleetFuel.assets',
[
'companyName' => $companyName,
'assets' => $assets
]
);
And then accesed it in the blade view:
<td width="20%" class="filter_make">{{ (isset($asset['AssetMakeName'])) ? ($asset['AssetMakeName']) : ("No make available")}}</td>
I cannot wrap my mind around something.
I have a table which I render in my tables.blade.php file like this:
<table>
<thead>
<tr>
<th scope="col">Country</th>
<th scope="col">Member</th>
</tr>
</thead>
<tbody>
#foreach ($members as $member)
#if ($member->continent == 'Europe')
<tr>
<td>
{{ $member->country }}
</td>
<td class="align-middle player-code copy-code">
{{ $member->name }}
</td>
</tr>
#endif
#endforeach
</tbody>
</table>
As you can see you can click on a country which will show you members from one country in a new view (code not shown here).
The route for that single country site in the web.php looks like this:
Route::get('/{country}', 'PageController#show')->name('country');
Everything worked fine until I realized that I could put anything as 'country' and still would get shown the site for the country just with an empty table.
So '/abcde' would get you the view with just a naked table.
So I changed the route like this:
Route::get('/{country}', 'PageController#show')->name('country')->where('country', ('United Kingdom|France|Belgium|South Africa);
//the list is much longer
Ok. So now I have constrained the 'country'-parameter in a pretty static way. And I have the feeling that is not the way it should be done. Because in the end I would like to have URLS that look like this '/united-kingdom', '/france', but now they're looking like this '/United%20Kingdom'.
I saw the answers to this question Laravel clean links without spaces or uppercase , but for me they're not so useful since I'm not working with Eloquent models but the Query Builder (The db tables I get are ready made, I only have to display them).
So my questions are:
How to limit a route parameter more dynamically?
How to display data one way (written like it's also in the table like this 'United Kingdom'), but have a route like this ('united-kingdom')?
I am willing to provide more code or info if you need, I'm just pretty confused and have the feeling I'm overlooking something (big).
Thank you for your time and help!
If you would like a route parameter to always be constrained by a
given regular expression, you may use the pattern method. You should
define these patterns in the boot method of your RouteServiceProvider:
use Illuminate\Support\Facades\DB;
//...
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$list_of_countries = DB::table('members')->whereNotNull('country')->pluck("country")->unique()->map(function ($name) {
return str_slug($name, '-');
})->reject(function ($name) {
return empty($name);
})->toArray();
$regex = '(' . implode('|', $list_of_countries) . ')';
Route::pattern('{country-slug}', $regex);
parent::boot();
}
routes\web.php
Route::get('/{country-slug}', 'PageController#show')->name('country');
Docs
I'm working on updating a laravel blade template to insert some database info into an html table. IN order to do this, I'm having to add new data to the controller for this blade and that's where I'm having some troubles.
I'm still trying to understand more with laravel, so I'm thinking my syntax or methods of creating this data are incorrect but I just can't put my finger on it right now.
In my function below, the $calls_allowed portion was already existing and it works on the page currently. I created the $contact_events portion of the function and that's where my problem is.
IN my view, I created a foreach loop and if statement around the html table in question. The table loads, but it's empty even though there are records in the database for the dealer.
I'm trying to say
if $dealer-> id matches contact_events.dealer_num, load all records for that dealer
contact_events is the table and dealer_num is the column I'm matching, then I'm trying to load the columns from that table (updated_at,method,notes) into the html table.
The affected code is below. The view/route/controller work, it's just this function I'm creating that isn't loading data. Any help is much appreciated.
Controller code:
public function show($id)
{
$d = Dealer::find($id);
if(!$d){
\Session::flash('warning_message', 'Sorry that resource can not be found.');
return redirect()->route('account.dealer.index');
}
$calls_allowed = DB::table('dealers.dealers')->
where('dealer_num', $id)->
pluck('calls_allowed');
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
if(!empty($calls_allowed)){
$d->calls_allowed = $calls_allowed[0];
} else {
$d->calls_allowed = null;
}
return view('Account.Dealer.show')->with('dealer', $d);
}
View code:
<thead>
<tr>
<th>Contacted Date</th>
<th>Type of Contact</th>
<th>Call Notes</th>
</tr>
</thead>
#foreach($dealer->contact_events as $events)
#if($events->dealer_num = $dealer->id)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endif
#endForeach
It looks like you are not assigning the data to the object after retrieving from database.
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
// add this
$d->contact_events = $contact_events;
This seems like a perfect time to use the power of Laravel's Eloquent ORM...
Check out the with and has in the Laravel docs
This will require some finessing based on your needs, but it will be something like this:
$d = Dealer::where('id', '=', $id)
->with('contact_events')->first();
This uses Eloquent to get all of the contact_events that belong to the dealer with the $id.
Then you can do something like this
note: this assumes that calls_allowed is a record on the dealer table. if I misunderstood that, you can still run than you can include that just as you have it.
#if(!is_null($dealer->calls_allowed)
#foreach($dealer->contact_events as $events)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endForeach
#endif
Sorry for my English.
I want to make a record that would be deduced me the sum of all my orders, that is, folded string of orders and drew grouped by orders.
I have created a model "Sale", which comprises method AmountOrder
public function AmountOrder()
{
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(price*quantity) as total_sales'))
->value('total_sales');
return $AmountOrder;
}
and to deduce the code like this
#foreach ($sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->client->name }}
</td>
<td>
{{$sale->date}}
</td>
<td>
{{$sale->AmountOrder($sale)}}
</td>
<td>
{{$sale->debt($sale)}}
</td>
<td>
{{$sale->date_of_issue}}
</td>
</tr>
#endforeach
But the problem is that the query is performed on each line. I'm new to Laravel, but thought maybe you can solve this problem somehow more beautiful?
Thank you very much in advance!
You are probably talking about the Eager Loading.
From the docs:
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.
However, you will be not able to use the Eager Loading now, with this code in the AmountOrder method.
A simple google search, also, led me to this example of Eager Loading with aggregate functions/relationships.
It will be probably a good start to think and implement your solution.
you have wrong in your select :
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(sale_lines.price*sale_lines.quantity) as total_sales'))
->value('total_sales');
My relationship
class Sale extends Model
{
//Получаем товар в этой продаже
public function good()
{
return $this->belongsTo('App\Good');
}
}
class Good extends Model
{
//В каких закупках был этот товар
public function purchases()
{
return $this->hasMany('App\Purchase');
}
//Продажи с этим товаром
public function sales()
{
return $this->hasMany('App\Sale');
}
}
Is it correct?
In my model i create method
public function AmountOrderRelation()
{
return $this->belongsTo('App\Good')
->selectRaw('sum(price) as aggregate, id')
->groupBy('id');
}
In controller
$new_sales = Sale::with('AmountOrderRelation')->get();
#foreach ($new_sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->AmountOrderRelation }}
</td>
</tr>
#endforeach
But my relations is null. What's my mistake?
I did it!
public function AmountOrder()
{
return $this->HasOne('App\SaleLines')
->join('goods', 'sale_lines.good_id', '=', 'goods.id')
->selectRaw(DB::raw('SUM(price*quantity) as aggregate, sale_id'))
->groupBy('sale_id');
}
public function getAmountOrderAttribute()
{
// if relation is not loaded already, let's do it first
if ( ! array_key_exists('AmountOrder', $this->relations))
$this->load('AmountOrder');
$related = $this->getRelation('AmountOrder');
// then return the count directly
return ($related) ? (int) $related->aggregate : 0;
}
And in controller
$sales = Sale::with('AmountOrder')->get();