Laravel Backpack select2_from_ajax select change the result and default value - laravel

For the backpack-demo, I would like to show the ID and Title together.
For the search result no issue, selected at the select2 also no issue, the problem is after save, it will not display, it become blank.
How can I set it?
Like below
backpack-demo/app/Http/Controllers/Admin/MonsterCrudController.php
[ // select2_from_ajax: 1-n relationship
'label' => 'Select2_from_ajax', // Table column heading
'type' => 'select2_from_ajax',
'name' => 'select2_from_ajax', // the column that contains the ID of that connected entity;
'entity' => 'article', // the method that defines the relationship in your Model
'attribute' => 'id_title', // foreign key attribute that is shown to user
'model' => "Backpack\NewsCRUD\app\Models\Article", // foreign key model
'data_source' => url('api/article'), // url to controller search function (with /{id} should return model)
'placeholder' => 'Select an article', // placeholder for the select
'minimum_input_length' => 2, // minimum characters to type before querying results
'tab' => 'Relationships',
'wrapperAttributes' => ['class' => 'form-group col-md-12'],
],
backpack-demo/app/Http/Controllers/Api/ArticleController.php
if ($search_term) {
return Article::
selectRaw("CONCAT('Article ID: ', id,' | Title: ', Title) AS id_title, articles.*")
->where('title', 'LIKE', '%'.$search_term.'%')->paginate(10);
} else {
return Article::selectRaw("CONCAT('Article ID: ', id,' | Title: ', Title) AS id_title, articles.*")
->paginate(10);
}

The solution is at the Article Model create another accessor function
public function getIdTitleAttribute()
{
return 'Article ID: ' . $this->id . ' | Title: ' . $this->title;
}

Related

Laravel backpack select2_from_ajax setting my value as null after the correct value has been saved

Im having a weird problem.
Im using laravel backpack for an admin panel. There i use select2_from_ajax to list a values according to another field in create operation. It is showing up correctly as expected & i can select one too.
But after selection when i click save & back it gives me an error
That means my column doesn't allow to update to null right.
So when i go back & check the column it has saved the correct value.
But when default value of my column was null this error will not showup & db value would be changed to null.
This is my select2_from_ajax part.
$this->crud->addField([ // Select
'label' => "Link Type",
'type' => 'select_from_array',
'name' => 'link_type', // the db column for the foreign key
'options' => [1 => 'Product',0 => 'Collection'],
'allows_null' => false,
]);
$this->crud->addField([ // Select
'label' => "Link To", // Table column heading
'type' => "select2_from_ajax",
'name' => "link_to",
'entity' => 'link',
'attribute' => "name",
'data_source' => url('admin/itemtype'),
'placeholder' => "Select a item",
'minimum_input_length' => 0,
'include_all_form_fields' => true,
'dependencies' => ['link_type'],
]);
So why is it trying to set null value after the correct value?
Any help would be appreciated. Thanks.
My admin/itemtype function:
$search_term = $request->input('q');
$form = collect($request->input('form'))->pluck('value', 'name');
if ($search_term) {
if ($form['link_type'] == 0) {
$items = Collection::where('name', 'LIKE', '%' . $search_term . '%')->paginate(10);
} else {
$items = Product::where('title', 'LIKE', '%' . $search_term . '%')->paginate(10);
}
} else {
if ($form['link_type'] == 0) {
$items = Collection::paginate(10);
} else {
$items = Product::paginate(10);
}
}
return $items;

Insert row in parents and childs table laravel

Im so lost. I have table, model and controller named Navbar. Here I create navbar buttons. I made child table called "type_1". So "navbar" id goes to table "type_1" and its column called "navbar_id".
$form_data = array(
'tipas' => $tipas,
'p_id' => $p_id,
'name' => $request->title,
'text' => $request->text,
'img' => $name
);
navbar::create($form_data); //created parent row
Here navbar button is created. How can I create childs empty row with parent (navbar) id? Should I use models or I can do it here?
On your Parent model, you need to define a relation like this :
public function child()
{
return $this->hasMany(Child::class);
}
Now you can insert data with eloquent method like this :
$form_data = array(
'tipas' => $tipas,
'p_id' => $p_id,
'name' => $request->title,
'text' => $request->text,
'img' => $name
);
$q = Parent::create($form_data); //created parent row
$q->child()->create(['name' => 'John', 'email' => 'me#john.com']); // here parent_id will be created by the model
Official documentation of the create method

laravel 7 Validation unique multiple columns

how to viladate multiple columns
table name "exam_starts"
columns
id
exam_id
exam_multi_id
student_id
exam_class_id
exam_code_id
Status
class Student extends Model
{
// exam
public function exams(){
return $this->belongsToMany('App\Exam','exam_starts','student_id','exam_id')
->withPivot(['id','exam_multi_id','exam_class_id','exam_code_id','Attend','pass','Status'])-
>withTimestamps();
}
}
how to unique columns student_id and exam_class_id in table exam_starts ?
My Try in controller
class ExamClassController extends Controller
{
$this->validate($request, [
'exam_class_id' => [
'required',
'integer',
'unique:exam_startss,exam_class_id,'.$request->exam_class_id .',student_id' ,
],
'student_id' => 'bail|required|integer',
'exam_start_id' => 'bail|required|integer',
'exam_id' => 'bail|required|integer',
'exam_multi_id' => 'bail|required|integer',
'code' => 'nullable|string',
'student' => 'bail|required|string',
]);
}
this mysql resulte
(SQL: select count(*) as aggregate from `exam_starts` where `exam_class_id` = 1 and `student_id` <> 1)
Use Unique rule class and you can pass multiple wheres to it, to make an unique constraint that takes two columns.
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id);
Set it into validation like so
'exam_class_id' => [
'required',
'integer',
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id),
],

ListEntries in table for relationship on show page - backpack for laravel

Just new with backpack. I search on official site and googled it, but dit not found an answer
In laravel 7, using Backpack 4.1
My data model is : Customer has many addresses
Relationship is configured in the Customer model :
public function addresses()
{
return $this->hasMany(\App\Models\Address::class, 'user_id');
}
Relationship is configured in the Address model :
public function customer()
{
return $this->belongsTo(\App\Models\Customer::class);
}
public function country()
{
return $this->belongsTo(\App\Models\Country::class);
}
public function address_type()
{
return $this->belongsTo(\App\Models\AddressType::class);
}
In my customer show page, I would like to show all customer addresses in a table, just under the customer details.
So in my CustomerCrudController, I have implemented this method :
protected function setupShowOperation()
{
$this->crud->set('show.setFromDb', false);
$this->crud->addColumn(['name' => 'name', 'type' => 'text', 'label' => __('models/customers.fields.name'), ]);
$this->crud->addColumn(['name' => 'email', 'type' => 'email', 'label' => __('models/customers.fields.email'), ]);
$this->crud->addColumn([
'name' => 'addresses',
'label' => __('models/addresses.plural'),
'type' => 'table',
'columns' => [
'address_type_id' => __('models/addresses.fields.address_type'),
'address_type.name' => __('models/addresses.fields.address_type'),
'address1' => __('models/addresses.fields.address1'),
'address2' => __('models/addresses.fields.address2'),
'city' => __('models/addresses.fields.address2'),
'postal_code' => __('models/addresses.fields.address2'),
'country.name' => __('models/countries.singular'),
],
]);
}
When I go on my page : /admin/customer/3/show,
In my debugbar, I saw the query how load addresses
select * from `addresses` where `addresses`.`user_id` = 3 and `addresses`.`user_id` is not null
I have the table rendered with the corresponding number of lines from data in DB, but rows are blank.
Is this the correct way to do that ? What are the correct parameters ?
Is there a way to show a table with action buttons (show entry, edit) - same as in List view ?
Should it be implemented in another way ?
Hope I'm clear.
Thanks
Don't know if it is a laravel bug, but my solution was to create my own table blade, base on the file :
\vendor\backpack\crud\src\resources\views\crud\columns\table.blade.php
and have created my own :
\resources\views\vendor\backpack\crud\columns\address_table.blade.php
I have juste changed the file:40
#elseif( is_object($tableRow) && property_exists($tableRow, $tableColumnKey) )
to
#elseif( is_object($tableRow) && isset($tableRow->{$tableColumnKey}) )
now, in my CustomerCrudController.php :
protected function setupShowOperation()
{
$this->crud->set('show.setFromDb', false);
$this->crud->addColumn(['name' => 'name', 'type' => 'text', 'label' => __('models/customers.fields.name'),]);
$this->crud->addColumn(['name' => 'email', 'type' => 'email', 'label' => __('models/customers.fields.email'),]);
$this->crud->addColumn([
'name' => 'addresses',
'label' => __('models/addresses.plural'),
'type' => 'address_table', // my custom type
'model' => \App\Models\Address::class,
'entity' => 'addresses',
'columns' => [
'address_type_name' => __('models/addresses.fields.address_type'),
'postal_code' => __('models/addresses.fields.postal_code'),
'city' => __('models/addresses.fields.city'),
'address1' => __('models/addresses.fields.address1'),
'address2' => __('models/addresses.fields.address1'),
],
]);
}
And I've added an accessor in my model (Address.php)
public function getAddressTypeNameAttribute()
{
return "{$this->address_type->name}";
}
Don't know if there is a better way ...
Hope this will help others.
I use Laravel 8,
In addition for the answer above, and based on this answer https://stackoverflow.com/a/65072393 and https://stackoverflow.com/a/43011286/1315632 regarding PHP function property_exists vs Laravel magic methods to create dynamic properties and methods
After creating the overwrite column php artisan backpack:publish crud/columns/table
I change line 40 in file:\resources\views\vendor\backpack\crud\columns\table.blade.php into
#elseif( is_object($tableRow) && ( property_exists($tableRow, $tableColumnKey) || property_exists((object)$tableRow->toArray(), $tableColumnKey) ) )
adding OR checking from answer https://stackoverflow.com/a/65072393

Showing relation table fields with filters in yii2

I'm showing has many relation table value in my girdview as follows
[
'attribute' => 'Resume Title',
'value' => function($model, $key, $index) {
return implode(\yii\helpers\ArrayHelper::map(
$model->jobSeekerProfiles,
'job_seeker_profile_id',
'resume_title'
));
},
],
my table relation is
public function getJobSeekerProfiles()
{
return $this->hasMany(JobSeekerProfile::className(), ['user_id' => 'user_id']);
}
But how to make this column with filter and sortable ?

Resources