When using the select2 field/column type in Laravel Backpack, the list view displays the 'id' of the foreign entity instead of the foreign key required (in this case the 'name' of the Session).
Laravel 5.8.4, Backpack 3.4. I asked in GitHub and the response was that my relationships were incorrect in my models. I don't think that's the problem as the name loads in the edit view.
GradeCrudController
$this->crud->addColumn([
'label' => "Session",
'type' => 'select2',
'name' => 'session_id', // the db column for the foreign key
'entity' => 'session', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'model' => "App\Models\Session" // foreign key model
]);
Grade (Model)
public function session()
{
return $this->belongsTo('App\Models\Session');
}
Session (Model)
public function grades()
{
return $this->hasMany('App\Models\Grade');
}
As it's been a few days and nobody has responded, I thought I'd post the answer I came up with. Note that I highly doubt that this is the correct solution, but for my project it will do.
I added a Laravel Observer for the Grade Model. Once a user adds a new record, the observer visits the session table, pulls the name of the session using the key and adds it as a column to the Grades table.
Then in backpack I just display the 'name' column.
There has to be a better way than this... But for now it will do.
I see you're using a "select2" column type. That's not something Backpack provides by default - it only has a "select" column.
Most likely what happened is that Backpack loaded the "text" column, since it couldn't find a "select2" column. Hence, the ID.
Try changing "select2" to "select". It should work for you without any observers/anything else.
I was having a similar issue. I could not get the foreign key attribute to show up no matter what. I finally got it working by doing to following.
Add the foreign key to the belongsTo method. It should be the name of the column in that model that has the ID that is associated with in the belongsTo model.
public function session()
{
return $this->belongsTo('App\Models\Session','name');
}
One other item that I suggest is to make sure all columns that have foreign keys are set to the same data types in the database.
Related
So, i have a table called Items table and another table called item_quantities, on item_quantities ive a column named item_id which is connected to items table id. All the fillable properties on both tables are all in one form on the frontend, and i take care of the form fields on the backend
Whenever i try to update the quantity on the form which is from item_quantities's table with a form, i'm facing serious issue updating the item_quantities. getting Attempt to read property "item_id" on null.
It all started when i noticed a duplicate entries on the item-quantities table, so i deleted all the datas on it..
Here's is the form screenshot
The vue form
and the backend logic
public function saveData(Request $request, $id) {
// dd($request->name);
$updateGroceries = Item::where('id', $request->id)->get()->first();
$updateGroceries->update([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
]);
if($updateGroceries) {
$item_quantity = ItemQuantity::where('item_id', $updateGroceries->id) ?
ItemQuantity::where('item_id', $updateGroceries->id)->get()->first() :
new ItemQuantity;
if($item_quantity->item_id == null) {
$item_quantity->item_id = $updateGroceries->id;
}
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
}
}
I'M SO SORRY IF MY ENGLISH WAS'NT CLEARED ENOUGH
Thanks in anticipation
You can simply use firstOrNew() method. This will first find the item, if not exist create e new instance.
$item_quantity = ItemQuantity::firstOrNew(['item_id' => $updateGroceries->id]);
$item_quantity->quantity = $request->quantity;
$item_quantity->save();
Note that the model returned by firstOrNew() has not yet been persisted to the database. You will need to manually call the save method to persist it.
Actually your errors workflow as that:
$item_quantity=null;
$item_quantity->item_id;
You can do that with optional global helper:
optional($item_quantity)->item_id ?: 'default value';
I have two models:
Brands
Mods
I can display all brands via belongsTo function. Problem is when I try to save same brand two times, I get error duplicated entry.
This belongsTo is causing duplicated entry error when saving to DB two same brands.
Mods.php
public $belongsTo = [
'brand' => [\Slasher\Farming\Models\Brands::class, 'key' => 'id'],
];
This belongsToMany works, and save's data to DB, but is generating checkbox field (I only want to select one brand at one mod enty). I'm using pivot table for this relation.
Mods.php
public $belongsToMany =[
'brand' =>[
'Slasher\Farming\Models\Brands',
'table' => 'slasher_farming_mods_brands',
'order' => 'brand_name'
],
];
BelongsTo example: (Brands are visible and I can save them. But problem is when saving same brand for more than two times).
Error I get when saving with belongsTo.
I tried also creating inverse relationships on Brands model with (belongsTo and belongsToMany), but still getting this error.
What type of relation should I make, to save Brands as dropdown list and to fix this duplicate error?
If you're using a pivot table for your relation, then you should use $belongsToMany. Pivot table is only used for many-to-many relations.
I fixed this problem with changing column in the mods name brand to brand_id and also changing belongsTo relation. I just removed key, and it works like a charm. No need for pivot table here.
Mods.php
public $belongsTo = [
'brand' => ['Slasher\Farming\Models\Brands']
];
"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY' (SQL: update liam_blog_blogs set id = 3, liam_blog_blogs.updated_at = 2022-07-26 09:30:09 where id = 2)"
I have a create method that works fine, but it fails trying to create its relation:
public function create(array $article, string $note)
{
$art = $this->article->create($article);
print($art->id) // this line is for helping me to know if id is successfully generated. It works!
$this->article->note()->create([
'article_id' => $art->id, // the id desapears
'note' => $note
])
}
Console logs:
Integrity constraint violation: 1048 Column 'article_id' cannot be null (SQL: insert into notes (article_id, note, updated_at, created_at) values (?, TESTING, 2019-11-13 13:03:07, 2019-11-13 13:03:07))"
The field article_id is probably not a fillable attribute on the Note model.
You could also create the note like this, without adding article_id as a fillable attribute:
$art->note()->create([
'note' => $note
]);
Also make sure that the relations are defined correctly on the models. If an article can have many notes, there might be something wrong with your definitions, since note is currently singular. If it is a one to one relation everything might be fine.
You need to save your article. $art->save()
How can you display relationships fields and filter by in the list and update views?
lets say I have a transactions table
Id, customer_id, product_id, purchase_date, payment_status
a customer table
Id, first_name, last_name, email, password
a products table
Id, product_name, product_description, product_price, stock
for example. And I wanted to show in my transactions view:
ID, customer.first_name customer.last_name, product.product_name, purchase_date, payment_status
and wanted to filter the results by customer name and product name, I have read through the docs and cannot see how to achieve this.
In your CrudController in the setup() method :
$this->crud->setListView('your-custom-view');
If you want, you can use the default list view as a starter and modify it
you can find the default file in vendor/backpack/crud/src/resources/views/list.blade.php.
Don't modify it there because it will show on all Crud views..just take it as a template and save 'your-custom-view' in views.
Maybe this will be of help : https://laravel-backpack.readme.io/v3.3/docs/filters
Edit:
Instead of customer_id you want the customer first_name and so on right? This will do the trick:
In your TransactionCrudController:
$this->crud->addColumn([
// 1-n relationship
'label' => "customer", // Table column heading
'type' => "select",
'name' => 'customer_id', // the column that contains the ID of that connected entity;
'entity' => 'customer', // the method that defines the relationship in your Model
'attribute' => "first_name", // foreign key attribute that is shown to user
'model' => "App/Models/Customer", // foreign key model
]);
Is this what you are looking for? If not let me know.
I have table 3 tables, equipment(ID, name)
parameters(ID, name) and the pivot table equipment_parameter(equipment_id, parameter_id) , on my "Equipment" list view i need to add a column with the name of the parameter so i need to retrieve name from the Parameter table.
Equipment Model:
public function parametros(){
return $this->belongsToMany('App\Parametro','equipo_parametro','equipo_id',
'parametro_id')->withTimestamps();
}
Parameter model:
public function equipos(){
return $this->belongsToMany('App\Equipo','equipo_parametro','parametro_id',
'equipo_id')->withTimestamps();
}
i added this on equipmentCrudcontroller ,but have had no success.
$this->crud->addColumn([ // Select
'label' => 'Parametro',
'type' => 'select2',
'name' => 'equipo_id', // the db column for the foreign key
(not sure here since equipment foreign key is on pivot table????)
'entity' => 'parametros', // the method that defines the relationship in your Model
'attribute' => 'nombre', // foreign key attribute that is shown to user
'model' => "App\Parametro" // (doubt, there's a pivot table inbetween???) foreign key model
]);
If you are adding a column and have already run the previous migration you can create a new migration php artisan make:migration update_equipment_table inside of that, you can then do something like this
Schema::table('table', function (Blueprint $table) {
$table->string('column');
});
then rerun migrations php artisan migrate this will add the new column to your table.