Get dynamic values ​of dynamic arrays in a mode - php

I want to obtain the data of an Audit model, that within its columns old_values ​​and new_values ​​are stored arrays, but dynamic. When I do the foreach in the view it gives me the following error when wanting to show these columns:
ErrorException (E_ERROR) htmlspecialchars() expects parameter 1 to be string, array given (View: H:\DAF\resources\views\audit\index.blade.php)
I've already searched several blogs and they say how to do something similar but with static arrays, not with dynamic ones.
The Audit model is Laravel's vendor to audit called OwenIt\Auditing.
class Audit extends Model implements \OwenIt\Auditing\Contracts\Audit
{
use \OwenIt\Auditing\Audit;
/**
* {#inheritdoc}
*/
protected $guarded = [];
/**
* {#inheritdoc}
*/
protected $casts = [
'old_values' => 'json',
'new_values' => 'json',
'auditable_id' => 'integer',
];
}
Controller
<?php
namespace App\Http\Controllers;
use OwenIt\Auditing\Models\Audit;
class EstaticasController extends Controller {
public function audit() {
$audit = Audit::orderBy( 'id', 'DESC' )->get();
return view( 'audit.index', compact( 'audit' ) );
}
}
Vista
<table class="table table-bordered table-hover table-stripped">
<thead>
<tr>
<th>No</th>
<th>Operación</th>
<th>Tupla</th>
<th>Tabla</th>
<th>Valores antiguos</th>
<th>Valores Actuales</th>
<th>URL</th>
<th>IP</th>
<th>Creado</th>
<th>Actualizado</th>
</tr>
</thead>
<tbody>
<?php $no = 1 ?>
#foreach($audit as $item)
<tr>
<td>{{ $no++ }}</td>
<td>{{ $item->event }}</td>
<td>{{ $item->auditable_id }}</td>
<td>{{ $item->auditable_type }}</td>
<td>{{ $item->old_values }}</td>
<td>{{ $item->new_values }}</td>
<td>{{ $item->url }}</td>
<td>{{ $item->ip_address }}</td>
<td>{{ $item->created_at }}</td>
<td>{{ $item->updated_at }}</td>
</tr>
#endforeach
</tbody>
</table>
Image of Table
Image of DB with data

I think here is the issue:
// ...
// <td>{{ $item->auditable_type }}</td>
<td>{{ $item->old_values }}</td>
<td>{{ $item->new_values }}</td>
// <td>{{ $item->url }}</td>
// ...
The problem here is that, in order to print them in screen, the front-end is expecting the value to be string, but you are giving it an array. That's why the error is throw:
ErrorException (E_ERROR) htmlspecialchars() expects parameter 1 to be string, array given (View: H:\DAF\resources\views\audit\index.blade.php)
To solve it, you just have to iterate over the array to print every element of it:
#foreach ($item->old_values as $value)
<p>{{ $value }}</p>
#endforeach

Related

show a list of users in symfony

in my symfony project i have a function that shows a list of users based on their "roles"
here's the controller code
/**
* #Route("/admin", name="admin_index", methods={"GET"})
*/
public function index(): Response
{
$Admins=$this->getDoctrine()->getRepository(User::class)->findBy(['roles' => array('["ROLE_ADMIN"]')]);
return $this->render('back/admin/index.html.twig', [
'admins' => $Admins,
]);
}
and here's the render
<table class="table" >
<thead>
<tr>
<th>Id</th>
<th>Nom</th>
<th>Email</th>
<th>Tel</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for admin in admins %}
<tr name="elements" id="{{ 'admin'~ admin.id}}">
<td>{{ admin.id }}</td>
<td>{{ admin.nom }}</td>
<td>{{ admin.email }}</td>
<td>{{ admin.tel }}</td>
<td>{{ admin.photo }}</td>
<td>
</td>
</tr>
{% else %}
<tr>
<td colspan="10">Rien a afficher</td>
</tr>
{% endfor %}
</tbody>
</table>
the problem here is that he's not showing anything even if the database is fulll
here's the entity declaration
/**
* #var string
*
* #ORM\Column(name="roles", type="json")
* #Groups ("post:read")
*/
private $roles;
and here's a screenshot of table structure
enter image description here
i'm really stuck since the morning and i cant figure out why
Since the roles field is json, your findBy won't work that way.
You should create a function in your UserRepository.php class to select users by their roles using QueryBuilder
public function findByRole($role)
{
return $this->createQueryBuilder('u')
->andWhere('u.roles LIKE :role')
->setParameter('role', "%{$role}%")
->getQuery()
->getResult();
}
you can then call that function from your controller
$admins = $this->getDoctrine()->getRepository(User::class)->findByRole("ROLE_ADMIN");
I also suggest you utilize var_dump($admins); in your controller to see if Doctrine is returning anything to you in the first place.
You can even dump variables in twig {{ dump(admins) }}

How to use pluck to get specific data from other table in Laravel?

From SalesController, I want to get specific name from table Item and passed to HTML.
My controller looks like
public function index()
{
$items=Item::orderBy('name','ASC')->get()->pluck('name','id');
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales,'items',$items);
}
My HTML is
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Quantity</th>
<th>Total Price</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->items->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
</tr>
#endforeach
</tbody>
But I get the following error after trying to access the page:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\inventoryApp\resources\views\Sale\index.blade.php)
there are two way
1.Using relationship
class Sale extends Model
{
public function item()
{
return $this->belongsTo('App\Item','item_id','id');
}
}
so you can use like below
<td>{{ $sale->item->name }}</td>
2. Using array data
public function index()
{
$items=Item::orderBy('name','ASC')->pluck('name','id')->toArray();
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales,'items',$items);
}
<td>{{ $items[$sale->item_id] }}</td>
$items=Item::orderBy('name','ASC')->pluck('name','id');
and use $items directly without sale object
If you have relationship with table Sale.
Add this function to your Sale Class.
public function item()
{
return $this->belongsTo('App\Item');
}
In your controller you can use compact
public function index()
{
$items=Item::orderBy('name','ASC')->get();
$sales=Sale::all();
return view('Sale.index')->compact('sales','items');
}
And you can use Eager load to your HTML.
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->item->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
</tr>
#endforeach
</tbody>
You are getting this error because you are trying to get a property of item name that does not exist on the sale object. you can simply do it by eloquent relationship as follows:
On your sale model:
public function item()
{
return $this->belongsTo('App\Item','item_id');
}
On your controller:
public function index()
{
$sales=Sale::all();
return view('Sale.index',compact('sales'));
}
Then on your blade you can easily get related Item name:
#foreach($sales as $sale)
<tr>
<td>{{ $sale->item->name }}</td>
</tr>
#endforeach

Database sql server with results but view is empty

something really strange is happening. So I have a table named Lactinfo_News with 1 row. I've created also a view called LACTINFO_VW_LatestNews which have "SELECT * FROM Lactinfo_News" and is returning the same 1 row.
I'm using Eloquent and In my news Manager I have,
public function GetLatestNews($rowsPerPage) {
$list = DB::table('LACTINFO_VW_LatestNews')
->orderBy('RegistedDate', 'DESC')
->paginate($rowsPerPage);
return $list;
}
where $rowsPerPage = 30.
In my controller I have,
// >> current page
$page = '1';
if (! empty ( $request->query ( 'page' ) )) {
$page = $request->query ( 'page' );
}
// >> search
$nM = new NewsManager();
$list = $nM->GetLatestNews($page, $this->nbOfRowsPage);
return view ('admin.news.index', [
'results' => compact($list),
'page' => $page,
'startDate' => $startDate,
'endDate'=>$endDate
] );
}
And in my view,
<table id="news-results" class="hover responsive" style="margin-top: 20px;">
<thead>
<tr>
<th scope="column">Título</th>
<th scope="column">Descrição</th>
<th scope="column">Data Início</th>
<th scope="column">Ficheiro</th>
<th scope="column">Registada em</th>
<th scope="column">Criada por</th>
</tr>
</thead>
<tbody>
#if (count($results) > 0)
#foreach ($results as $r)
<tr>
<td>{{ $r->title }}</td>
<td>{{ $r->description }}</td>
<td>{{ Carbon\Carbon::parse($r->startDate)->format('d/m/Y') }}</td>
<td>{{ $r->fileURL }}</td>
<td>{{ $r->registedDate }}</td>
<td>{{ $r->createdBy }}</td>
</tr>
#endforeach
#else
<tr><td colspan="11">Não existem notícias criadas</td></tr>
#endif
</tbody>
</table>
If I dump the $results var is empty..
What's happening? This is really strange :S I don't think I need to execute any artisan command because I've add a new function to my manager but I'm stuck with this problem for a few days...
You are using compact on an object of type LengthAwarePaginator, which is kind of weird IMHO.
Why don't you pass $list in your view?
My problem was in the Controller and in my View,
So I've changed my controller return to
return view ('admin.news.index', [
'results' => $list,
'page' => $page,
'startDate' => $startDate,
'endDate'=>$endDate
] );
And in my view I wasnt calling in a wrong way my parameters...
<tbody>
#if (count($results) > 0)
#foreach ($results as $r)
<tr>
<td>{{ $r->Title }}</td>
<td>{{ $r->Description }}</td>
<td>{{ Carbon\Carbon::parse($r->StartDate)->format('d/m/Y') }}</td>
<td>{{ $r->fileURL }}</td>
<td>{{ Carbon\Carbon::parse($r->RegistedDate)->format('d/m/Y') }}</td>
<td>{{ $r->refCredential }}</td>
</tr>
#endforeach
#else
<tr><td colspan="11">Não existem notícias criadas</td></tr>
#endif
</tbody>

Obtaining field from table using primary key

Using Laravel and Revisionable Package for tracking changes. In my view I'm populating my table:
#foreach($revisions as $revision)
#if($revision->key == 'created_at' && !$revision->old_value)
<tr>
<td>{{ $revision->revisionable_type }}</td>
<td>{{ $revision->revisionable_id }}</td>
<td width="50">{{ $revision->userResponsible()->first_name }}</td>
<td Width="50"></td>
<td></td>
<td>{{ $revision->newValue() }}</td>
<td width="150">{{ $revision->created_at }}</td>
</tr>
#else
<tr>
<td>{{ $revision->revisionable_type }}</td>
<td>{{ $revision->revisionable_id }}</td>
<td width="50">{{ $revision->userResponsible()->first_name }}</td>
<td width="50">{{ $revision->fieldName() }}</td>
<td>{{ $revision->oldValue() }}</td>
<td>{{ $revision->newValue() }}</td>
<td width="150">{{ $revision->updated_at }}</td>
</tr>
#endif
#endforeach
The second column {{ $revision->revisionable_id }} happens to be the primary key of the user record that was modified. I would like to return the email address or first_name/last_name of that users record. I'm fairly new at this and could use a push in the right direction!
Thanks!
You can access the model that given revision relates to by accessing the revisionable relation of that revision. In your case, in order to display the email property of related model, you could do the following:
<td>{{ $revision->revisionable->email }}</td>
from the variable names revisionable_type & revisionable_id I assume you're using many to many Polymorphic relation. based on that
you've to define a relation in the Revision Model with the User like so:
public function users()
{
return $this->morphedByMany('App\User', 'taggable');
}
so you can use all the revisions related to this user $revision->users this will return array
and if you're sure that you've only one record related to this object like your case as I think. you can use $revision->users->first()->email or username, etc..
Laravel Docs

Laravel 4.2 DB returning all records

I am using Laravel 4.2 and catching single data from DB, because foreach loop is giving me last record all time
This is foreach in my blade.php file:
#foreach($vrataMreze as $vrataMrezeVar)
<tr>
<td>{{ $vrataMrezeVar->nalogBroj }}</td>
<td>{{ $vrataMrezeVar->nazivNaloga }}</td>
<td>{{ $vrataMrezeVar->narucitelj }}</td>
<td>{{ $vrataMrezeVar->datumIzrade }}</td>
<td>{{ $vrataMrezeVar->statusProizvodnje }}</td>
<td>{{ $vrataMrezeVar->datumOtpreme }}</td>
<td>{{ $vrataMrezeVar->nacinOtpreme }}</td>
<td>{{ $vrataMrezeVar->statusPoslovnice }}</td>
<td>{{ $vrataMrezeVar->datumMontaze }}</td>
<td>{{ $vrataMrezeVar->montirano }}</td>
<td>{{ $vrataMrezeVar->isporuceno }}</td>
<td align="center"><span class="glyphicon glyphicon-ok"></span></td>
<td align="center"><span class="glyphicon glyphicon-trash"></span></td>
<td align="center"><span class="glyphicon glyphicon-edit"></span></td>
<td align="center"></span></td>
</tr>
Route for this action:
Route::get('/nalozi/mreze/vrataMrezaOpen', array('uses' => 'MrezeController#openVrataMreza', 'as' => 'openVrataMreza'));
And function from my controller:
public function openVrataMreza($id)
{
$vrataMreze = DB::table('VrataMreza')->where('id', $id)->first();
return View::make('nalozi.Mreze.Vrata_Mreze.vrataMrezaOpen')->with('vrataMreze', $vrataMreze);
}
Also I tried with
Session::set('id', $vrataMrezeVar->id);
and
Session::get('id');
but didn't work, aslo get last record from database..
Your question is not much clear , but to get last record you can modify eloquent query.
public function openVrataMreza($id)
{
$vrataMreze = DB::table('VrataMreza')->where('id', $id)->orderBy('id','DESC')->first();
return View::make('nalozi.Mreze.Vrata_Mreze.vrataMrezaOpen')->with('vrataMreze', $vrataMreze);
}

Categories