php - Display email column from another table instead of referencing ID in laravel backpack
3 of the tables in my database are:
- Orders
- Products
- User
This is the migration of orders table
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained(); // FK to Users table
$table->foreignId('product_id')->constrained(); // FK to product table
// ...
$table->timestamps();
});
}
Now when I am Listing all the data in my Admin panel, I want to display:
email(which is unique) from user Table instead ofuser_idproduct_name(which is also unique) from products Table instead ofproduct_id
app/Http/Controllers/Admin/OrderCrudController.php
[
'name' => 'user_id', // Table column which is FK for Customer table
'label' => 'User', // Label for HTML form field
'type' => 'select2', // HTML element which displaying transactions
'placeholder' => 'Select a User', // placeholder for the select
'allows_null' => true,
'attribute' => 'email', // Column which user see in select box
'minimum_input_length' => 1,
'hint' => 'The person who ordered the product',
],
[
'name' => 'product_id',
'label' => 'Product',
'type' => 'select',
'placeholder' => 'Select a Product', // placeholder for the select
'allows_null' => true,
'attribute' => 'name', // Column which user see in select box
'minimum_input_length' => 1,
'hint' => 'The product which was ordered',
],
]
When I use the above code in protected function setupCreateOperation(), it gives me the desired results.
But protected function setupListOperation() displays the referencing id and Not the email id.
Now, you can see I have used
'type' => 'select2'in user_id'type' => 'select'in product_id
If I use select, it shows the expected column even in setupListOperation. But select2 does Not.
My main question is:
How can I display email column from another table instead of referencing ID using select2 in setupListOperation
Using Laravel Framework 8.61.0 and trying this for a long time. Any help is appreciable. Thanks in advance :)
Answer
Solution:
in setupListOperation you use Columns
there is no column in Backpack called "select2", in the end, columns are read-only and users can not input data for columns.
to display user's email, you can use select column:
[
'label' => 'email', // Table column heading
'type' => 'select',
'name' => 'user_id',
'key'=>'email'
'entity' => 'user', // the method that defines the relationship in your Model
'attribute' => 'email', // foreign key attribute that is shown to user
'model' => User::class, // foreign key model
],
make sure you have user() relation in your Order model.
Source
