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) }}
Related
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
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
Hello I cannot un delete my data why is it? here is my code
on the Controller
public function displayArchive()
{
$clients = Client::withTrashed();
return view('admin.clients.homeArchive')->with('clients', $clients);
}
one the View
<table class="table table-bordered" id="dynamic_field">
<tr>
<th>Client Code</th>
<th>Client Name</th>
<th>Address</th>
<th>Tel No.</th>
<th>Contact Person</th>
<th>Mobile No.</th>
<th>Email Address</th>
<th>Website</th>
<th>Status</th>
<th>Update</th>
</tr>
#foreach ($clients as $client)
<tr>
<td>{{ $client->client_code }}</td>
<td>{{ $client->client_name }}</td>
<td>{{ $client->address }}</td>
<td>{{ $client->tel_no }}</td>
<td>{{ $client->contact_person }}</td>
<td>{{ $client->mobile_no }}</td>
<td>{{ $client->email_ad }}</td>
<td>{{ $client->website }}</td>
<td>Inactive</td>
<td></td>
</tr>
#endforeach
</table>
on the Web
Here you can see how I call my controller and view pages.
Route::get('/admin/clients/homeArchive', 'Admin\ClientsController#displayArchive');
EDITED
Here is the edited code please take a look
my Model
use SoftDeletes;
protected $dates = ['deleted_at'];
// Table Name
protected $table = 'clients';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
Can you try with ->get() method.
public function displayArchive()
{
$clients = Client::withTrashed()->get();
return view('admin.clients.homeArchive')->with('clients', $clients);
}
NOTE: it don't undelete any data. it only get data with deleted rows.
If you want recover deleted data, you must use ->restore() method.
For all restored all data;
Link:
Inactive
Route:
Route::get('/admin/clients/restore-all', 'Admin\ClientsController#restoreAll')->name('admin.client.restore_all');
Controller action:
public function restoreAll(){
Client::withTrashed()->restore();
}
Restore row by row data;
Link:
Inactive
Route:
Route::get('/admin/clients/restore/{client}', 'Admin\ClientsController#restore')->name('admin.client.restore');
Controller action:
public function restore(Client $client){
$client->restore();
}
$client->id is the client collection, I think you want to inactive in the listed foreach row, is right?
I am retrieving all Tickets assigned to a user. A single ticket has a foreign key to users table. These are the code below:
App\Models\User.php
protected $appends = ['full_name', 'avatar'];
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
App\Http\Controllers\TicketsController.php
/**
* Display a listing of the resource.
*/
public function index()
{
$tickets = Ticket::paginate(25);
$users = User::all();
//return view('user.tickets.index', compact('tickets'));
return View::make('user.tickets.index', compact('tickets','users'));
}
Resources/Views/User/Tickets/index.blade.php
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Status</th>
<th>Assigned To</th>
</tr>
</thead>
<tbody>
#foreach($tickets as $item)
<tr>
<td>{{ $item->status }}</td>
<td>{{ $item->user_id }}</td>
</tr>
#endforeach
</tbody>
</table>
I want to convert the field {{ $item->user_id }} into {{ $item->first_name where id = $item->user_id }} The field should be converted into the First Name according to the $item->user_id
user_id is a foreign key to tickets and the equivalent of it is the is of Users table.
Please help.
Firstly it's not good practice to write db query in views. You can accomplish that by defining a relation in your Ticket model class.
public function user()
{
return $this->belongsTo(User::class);
}
Now you can access user name by $item->user->first_name.
Try this:
#foreach (DB::table('table_name')->where('id', '=', $tickets->id)->get() as $id)
{{ $id->id }}
{{ $item->column_val1}}
{{ $item->column_val2}}
{{ $item->column_val3}}
#endforeach
I have a 3 tables that I am joining together, "PurchaseOrderProductsStatus, Product and PutAway" tables.
PurchaseOrderProductsStatus Table
id | product_id |
----------------------
10 | 1 |
Product Table
id | Name |
---------------------------
1 | Acme Product 123
PutAway Table
id | product_id |
----------------------
100 | 1
101 | 1
I am able to output the data to the screen, the issue I am running into is that it is only returning 1 row from my PutAway table. It should return 2 rows like so...
Acme Product 123
100 - Acme Product 123
101 - Acme Product 123
Here is my customQuery. What Am I doing wrong?
$query = $this->getEntityManager()
->createQuery('
SELECT pops, pr, pa
FROM WIC\PurchaseOrderBundle\Entity\PurchaseOrderProductsStatus pops
LEFT JOIN pops.product pr
LEFT JOIN pr.putAway pa
WHERE pops.inventoryLocation = :id
AND pops.account = :account_id
')
->setParameter('id', $id)
->setParameter('account_id', $account_id);
Just a bit of information on my set up. In my Product Entity I have a oneToMany Association for the PutAway table.
/**
* #ORM\OneToMany(targetEntity="WIC\InventoryBundle\Entity\PutAway", mappedBy="product", fetch="EAGER")
*/
protected $putAway;
public function __construct()
{
$this->putAway = new ArrayCollection();
}
Here is my twig template:
{% for action in productActions %}
<tr>
<td>{{ action.product.id }}</td>
<td>{{ action.product.sku }}</td>
<td>{{ action.product.name }}</td>
<td>{{ action.qty }}</td>
<td>0</td>
</tr>
<tr>
<td colspan="5">
<div class="row-fluid">
<div class="span2">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Purchase Order</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="span10">
<table class="table table-bordered" id="put_away_{{ action.product.id }}">
<thead>
<tr>
<th>Put Away Location</th>
<th>Quantity</th>
<th>Date</th>
<th>Entered By</th>
</tr>
</thead>
<tbody>
{% for putAway in action.product.putAway %}
<tr class="info">
<td>{{ putAway.inventoryLocation.name }}</td>
<td>{{ putAway.qty }}</td>
<td>{{ putAway.created|date("m/d/Y") }}</td>
<td>{{ putAway.createdBy.firstName }} {{ putAway.createdBy.lastName }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</td>
</tr>
{% endfor %}
I see that you have defined the following relation:
/**
* #ORM\OneToMany(targetEntity="WIC\InventoryBundle\Entity\PutAway", mappedBy="product", fetch="EAGER")
*/
protected $putAway;
The mappedBy="product" tells me that PutAway entity has the product property - probably defined as #ManyToOne (the opposite).
As you may know, in relations if you omit the #JoinColumn (or #JoinTable for many-to-many) Doctrine will assume the default column names and try to join the tables. However, this may produce the unexpected results (such as yours).
Now the important part: If you want to ensure the correct columns are being used you need to set #JoinColumn annotation on one side of relation. In your example:
Product entity
/**
* #ORM\OneToMany(targetEntity="WIC\InventoryBundle\Entity\PutAway", mappedBy="product", fetch="EAGER")
* #ORM\JoinColumn(name="id", referencedColumnName="id_product")
*/
protected $putAway;
The alternate solution would be:
PutAway entity
/**
* #ORM\ManyToOne(targetEntity="WIC\InventoryBundle\Entity\Product", inversedBy="putAway", fetch="EAGER")
* #ORM\JoinColumn(name="id_product", referencedColumnName="id")
*/
protected $product;
In #JoinColumn annotation:
name represents the local (hm, some better term maybe) column
referencedColumnName represents the foreign column
Will this work?