create nested droptown using laravel admin panel - laravel

i have a table buss_catgry_mst
fields:- buss_catgry_mst_id , category_name ,parent_id, depth.
i want to create nested category using select_2_nested in backpack laravel.
ex:-
buss_catgry_mst_id=1 , category_name=restaurent ,parent_id=0, depth=1.
i want to create it's sub category and i want to take depth value which is +1 from it's main category depth value.
code in crud controller:-
{
CRUD::setValidation(StoreRequest::class);
//for nested
CRUD::addField([
'name' => 'parent_id',
'label' => "Category",
'type' => 'select2_nested',
'entity' => 'category', // the method that defines the relationship in your Model
'attribute' => 'category_name', // foreign key attribute that is shown to user
'model' => "App\Models\BussCatgryMst",
]); ```
***model buss_catgry_mst***
public function category()
{
return $this->hasMany(BussCatgryMst::class);
}
public function children()
{
return $this->hasMany('App\Models\BussCatgryMst','parent_id');
}

Related

Many-To-Many Relationship in backpack 4.1 for laravel

I use laravel 8 and backpack 4.1 for laravel. I have to add in one column more then one comma-separated-values. I have one pivot table with 2 foreign keys. The user can see with foreign key the available objects. I have to put all available objects into one column in setupListOperation() in CrudController of the user. How can I do it?
UserModel:
public function Objects(): belongsToMany
{
return $this->belongsToMany(Object::class);
}
CRUD::column('object_id')
->type('relationship')
->relation_type('BelongsToMany')
->model(Object::class)
->entity('name')
->label('Objects');
Thank you for your answers in advance.
I have found another method for the user crud. This method supposed to get the values from the method of the model.
$this->crud->addColumn(
[
// run a function on the CRUD model and show its return value
'name' => 'rentalObjects',
'label' => 'RentalObjects', // Table column heading
'type' => 'model_function_attribute',
'function_name' => 'getRentalObjects',
'attribute' => 'name'
]);
Method in the model User:
public function getRentalObjects(): string
{
$users = User::all();
foreach ($users as $user) {
$rentalObjects = $user->rentalObjects;
foreach ($rentalObjects as $rentalObject) {
$objectsNames = $rentalObject->name;
}
$objects = implode(",", array($objectsNames));
}
return $objects;
}
I coudn't see the new column on the small screen und thought, that the column wasn't in the table. By backpack one can choose the columns, if the screen is small.
The problem was solved:
$this->crud->addColumn([
'label' => 'Objekte', // Table column heading
'type' => 'select_multiple',
'name' => 'rentalObjects', // the method that defines the relationship in your Model
'entity' => 'rentalObjects', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'model' => 'App\Models\RentalObject', // foreign key model
]);

Eloquent eager loading specific columns

I have two models :Product and category
which are linked by a one-to-many relationship. A category has several products. I would like to select specific columns from each model.
Here is the query I have, but I have all the columns with category_id, but I want the category name instead of id. How can I do that. Thank you in advance.
here is the method in controller
$products = Product::with('categories:id,name')->get();
if ($products) {
$response = ['api_status' => 1, 'api_message' => 'success', 'data' => $products];
return response()->json($response);
} else {
$response = ['api_status' => 0, 'api_message' => 'Error'];
return response()->json($response);
}
Here is category model
class Categorie extends Model
{
use HasFactory, SoftDeletes;
protected $fillable =['name','redirect'];
public function products()
{
return $this->hasMany(product::class);
}
}
and the product model is:
class Product extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'name',
'description',
'detail', 'img',
'categorie_id', 'onSale',
'costPrice', 'inStock', 'salePrice'
];
public function categories()
{
return $this->belongsTo(Categorie::class);
}
}
here is the response:
To modify the output of your model I'd suggest using an API resource. This will give you more granular control about how a resource is returned by the API. A resource is also the best point to modify certain values.
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'detail' => $this->detail,
'img' => $this->img,
'category_id' => $this->categorie->name,
'category_name' => $this->categorie->name,
'onSale' => $this->onSale,
'costPrice' => $this->costPrice,
'inStock' => $this->inStock,
'salePrice' => $this->salePrice,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'deleted_at' => $this->deleted_at,
'categories' => $this->categories ?? null,
];
}
}
This way you can manually specify which values your response should have.
In your controller you can include the populated array in your response by manually filling the toArray method with the current request object or just by using the resolve method which basically does the previous task for you:
$response = [
'api_status' => 1,
'api_message' => 'success',
'data' => ProductResource::collection($products)->resolve()
];
You can select particular fields from the relationship but you always need to select any keys involved in the relationship:
$products = Product::with('categories:id,name')->get();
Now each Product has its 'categories' loaded and those Category models only have the id and name fields.
Importantly:
The relationship categories is named incorrectly, it should be categorie in this case as the foreign key on Product is categorie_id and it is a singular relationship, it does not return multiple results.
Product::with('categorie:id,name')->get()
If you want to keep the name categories you would have to define the foreign key used when defining the belongsTorelationship, the second argument.
If you need to transform the structure of any of this that is a different thing and you will be walking into transformers or an API Resource.
Not sure how you want your data to look but this is the structure you will have by eager loading records, so if you need a different structure then what you get you will have to show an example.

Adding Columns with nested relationships in backpack for laravel

I have 3 models created in backpack for laravel CRUD:
Driver, Municipality and Province.
Driver has a 'municipality_id' and the relationship function:
public function municipality()
{
return $this->belongsTo('App\Models\Municipality');
}
To get the province of the driver i need to use a relationship function inside Municipality model:
public function province()
{
return $this->belongsTo('App\Models\Province');
}
The driver model does not contain the province function so i have to to something like
$objdriver->municipality->province->name;
To get the province name.
Now the problem is that i have to add 2 columns in the table created by artisan that display the municipality name and the province name.
For the municipality it's easy and i did it like this:
$this->crud->addColumn('municipality_id', [
// 1-n relationship
'label' => "Comune", // Table column heading
'type' => "select",
'name' => 'municipality_id', // the column that contains the ID of that connected entity;
'entity' => 'municipality', // the method that defines the relationship in your Model
'attribute' => "name", // foreign key attribute that is shown to user
'model' => "App\Models\Municipality", // foreign key model
]);
And it works Fine, but how do i add a column for the Provinces? Since the method is not in the driver model i can't use the same approach.
I already tried using a custom function to fetch what i need from the province table, something like:
$this->crud->addColumn('province_id', [
// run a function on the CRUD model and show its return value
'name' => "province_id",
'label' => "Provincia", // Table column heading
'type' => "model_function",
'function_name' => 'GetProvinceName', // the method in your Model
])
where GetProvinceName is:
public function GetProvinceName()
{
return $this->municipality->province->name;
}
but that just gives out an error.
You could try the following code.
$this->crud->addColumn([
'name' => 'municipality.province.name', // the relationships are handled automatically
'label' => 'Provincia', // the grid's column heading
'type' => 'text'
]);

Include related table from pivot table in Fractal's Transformers

In my Laravel project, I have 4 tables:
location
location_product
product
status
location_product is the intermediate table between location and product and it has a foreign key status pointing to the product_status table.
I'm using Fractal's transformers to transform my models:
//Filter the products
$products = $location->products()->unarchived()->get();
return $this->response()->collection($products, new ProductDetailsTransformer());
and in my ProductDetailsTransformer.php, I want to include the status from the intermediate table using '''defaultIncludes''':
/**
* List of resources to automatically include
*/
protected $defaultIncludes = [
'status',
];
public function includeStatus(Product $product) {
return $this->item($product->pivot->status, new ProductStatusTransformer());
}
but I receive an
Call to undefined relationship [status] on model [App\Models\Product].
How can I correctly include the status table using Fractal's transformers?
At the moment, I'm using the following:
public function transform(Product $product) {
return [
'id' => (int)$product->id,
'name' => $product->name,
'amount' => $product->pivot->amount,
'delivery_on_site' => (bool)$product->pivot->delivery_on_site,
'status' => [
'id' => $product->pivot->status->id,
'name' => $product->pivot->status->name
]
];
}
But I'd like to use a Transformer if that's possible for the status.

ErrorException in CrudTrait.php Undefined offset: 0 Backpack for Laravel 5.2

i want create dynamic combobox from database, but i have an error with this message :
ErrorException in CrudTrait.php line 32: Undefined offset: 0 (View: /home/vagrant/Code/hrd/resources/views/vendor/backpack/crud/fields/select2.blade.php) (View: /home/vagrant/Code/hrd/resources/views/vendor/backpack/crud/fields/select2.blade.php) (View: /home/vagrant/Code/hrd/resources/views/vendor/backpack/crud/fields/select2.blade.php)
This is my DistrictCrudController.php :
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use App\Http\Requests\DistrictRequest as StoreRequest;
use App\Http\Requests\DistrictRequest as UpdateRequest;
class DistrictCrudController extends CrudController {
public function __construct() {
parent::__construct();
$this->crud->setModel("App\Models\District");
$this->crud->setRoute("admin/district");
$this->crud->setEntityNameStrings('district', 'districts');
$this->crud->setFromDb();
$this->crud->addField([
'label' => "City",
'type' => 'select2',// the method that defines the relationship in your Model
'name' => 'city_id', // the db column for the foreign key
'entity' => 'cities', //tabel entity
'attribute' => 'id', // foreign key attribute that is shown to user
'model' => "App\Models\City" // foreign key model
]);
}
public function store(StoreRequest $request)
{
return parent::storeCrud();
}
public function update(UpdateRequest $request)
{
return parent::updateCrud();
}
}
The code is run well if i remove :
$this->crud->addField([
'label' => "City",
'type' => 'select2',// the method that defines the relationship in your Model
'name' => 'city_id', // the db column for the foreign key
'entity' => 'cities', //tabel entity
'attribute' => 'id', // foreign key attribute that is shown to user
'model' => "App\Models\City" // foreign key model
]);
I use Backpack for Laravel 5.2
Not sure if it will solve, but i can only see two issues that might be causing that.
You don't have cities relationship defined or you could try using:
public function setUp()
{
$this->crud->setModel("App\Models\District");
$this->crud->setRoute("admin/district");
$this->crud->setEntityNameStrings('district', 'districts');
$this->crud->setFromDb();
...
...
don't use parent::__construct().
Give it a try and post your results if not solved.

Resources