Cannot apply individual column searching with Chumper Datatables and Laravel - laravel-4

I am stuck on the following,
I am using Chumper/datatable to display data from a MySQL database using PHP Laravel.
As descriped I have created two routes, One to deliver the view to the user, the other for datatable data:
Route::resource('users', 'UsersController');
Route::get('api/users', array('as'=>'api.users', 'uses'=>'UsersController#getDatatable'));
Then the controller
public function getDatatable()
{
return Datatable::collection(User::all(array('id','name', 'address')))
->showColumns('id', 'name', 'address')
->searchColumns('name')
->orderColumns('id','name')
->make();
}
and in blade page
#extends ('layouts.main')
#section('content')
<h2>Users</h2>
<div id="User">
{{ Datatable::table()
->addColumn('id', 'name', 'address')
->setUrl(route('api.users'))
->render()
}}
</div>
#stop
The problem is that I cannot find a way to apply the individual column searching (select inputs) and search in all 3 columns.
Thank you
/magefi

If i understand you correctly, You can pass multiple fields to searchColumns()
Controller:
->searchColumns(array('id:char:255', 'first_name', 'last_name', 'address', 'email', 'age:char:255'))
Package:
Line 237 of vendor/chumper/datatable/src/Chumper/Datatable/Engines/BaseEngine.php
237: public function searchColumns($cols)
238 {
239 if ( ! is_array($cols))
....
From README.md:
searchColumns(..$fields)
Will enable the table to allow search only in the given columns.
Please note that a collection behaves different to a builder object.
Note: If you want to search on number columns with the query engine,
then you can also pass a search column like this ```
//mysql
->searchColumns(array('id:char:255', 'first_name', 'last_name', 'address', 'email', 'age:char:255'))
//postgree
->searchColumns(array('id:text', 'first_name', 'last_name', 'address', 'email', 'age:text')) ```
This will cast the columns int the given types when searching on this
columns

Related

Eloquent creating empty record

I'm sure I'm doing something wrong but can't figure out what it is.
In a controller I have a method which executes:
$estimate = Estimate::create(
['session_id' => 'test']
);
Model:
use HasFactory;
protected $fillable = ['width, height, direction_id, media_id, coating_id, shape_id, amount, qty, session_id'];
Estimate is related to estimates in my db.
When triggered an estimate record is created but the field 'session_id' is blank.
session_id is a VARCHAR 191.
Any idea why this is happening?
You define your $fillable wrong. It should be an array of strings:
protected $fillable = [
'width',
'height',
'direction_id',
'media_id',
'coating_id',
'shape_id',
'amount',
'qty',
'session_id',
];

Laravel 5.4 with Entrust: How to get users with roles

I am trying to get all users with roles, but "roles" field is always an empty array.
There are 4 users, 2 of them have at least 1 role attached, verified.
UserController.php
public function getUsers()
{
$users = User::select('name', 'email', 'type')->with('roles')->get();
return view('user.list', ['users' => $users, 'lang' => Lang::getLocale()]);
}
I get the 'roles' field as an empty array, even if I don't use "with->('roles')" in the controller. Weird?
If i print each user role in the view, I get this:
object(Illuminate\Database\Eloquent\Collection)#281 (1) { ["items":protected]=> array(0) { } }
What I am doing wrong?
You have to select also primary key, on which roles are related.
Eloquent is first selecting all users and then based on their IDS (primary and foreign) is selecting relations. If you dont select primary key, he cant relate relations.
$users = User::select('id', 'name', 'email', 'type')->with('roles')->get();
Also, if you want specifi which columns from roles you want, you have to select foreign key too.
$users = User::select('id', 'name', 'email', 'type')->with(['roles' => function ($query) {$query->select('id', 'name', 'user_id');}])->get();

How to sort on fields from contained associations when using the paginator?

How to use CakePHP to pagination on a paginated query? Data it's ok, but not working sort links....
In my controller:
$this->paginate = [
'contain' => ['Slaves.Devices','Measurements','AlarmTypes.FunctionTypes.Units'],
'maxLimit'=>50
];
$alarms=$this->AlarmGenerates->find()
->select([
'Slaves.name',
'Devices.name',
'AlarmTypes.nazwa',
'FunctionTypes.name',
'Measurements.value',
'AlarmTypes.max_value',
'AlarmTypes.min_value',
'Units.name',
'AlarmGenerates.created'
])
->contain(['Slaves.Devices','Measurements','AlarmTypes.FunctionTypes.Units']);
$alarmyAll=$this->paginate($alarms);
In template:
<th><?=$this->Paginator->sort('slave.device.name','Obiekt')?></th>
<th><?=$this->Paginator->sort('alarm_type.nazwa','Nazwa Alarmu')?></th>
<th><?=$this->Paginator->sort('name',null,['model'=>'FunctionTypes'])?></th>
<th><?=$this->Paginator->sort('measurement.value','Wartość',['model'=>'Measurement'])?></th>
<th><?=$this->Paginator->sort('alarm_type.max_value','Dopuszczalny przedzial')?></th>
<th><?=$this->Paginator->sort('created','Czas wystąpienia')?></th>
Pleas help...
You can add the columns that you want to be able to sort by to the paginate's whitelist:-
public $paginate = [
'contain' => ['Slaves.Devices', 'Measurements', 'AlarmTypes.FunctionTypes.Units'],
'maxLimit' => 50,
'sortWhitelist' => [
'slave.device.name',
'alarm_type.nazwa',
'name',
'measurement.value',
'alarm_type.max_value',
'created'
]
];
If you need to be able to sort on any columns from associated data then you need to define the columns in the sortWhitelist as mentioned in the official docs.
This option is required when you want to sort on any associated data, or computed fields that may be part of your pagination query

How to update a mass assignment model?

if I have a model Student and it has three properties:
name
age
classroom_id
name and age are in fillable array.
So if I want to create a new student and assign his/her classroom_id, I have to do this:
$student = App\Student::create(
[
'name'=>$request->input('name'),
'age'=>$request->input('age')
]
);
$student->classroom_id = 1;//for example
$student->save();
is this right? And if this is right, actually I do insert action twice, right?
You can just update your $fillable array inside your model to include classroom_id and it will become mass assignable, meaning you don't need to do two inserts to get all the data in there.
As such, your $fillable array will look similar to this:
protected $fillable = ['name', 'age', 'classroom_id'];
And your create method similar to this:
$student = App\Student::create(
[
'name' => $request->input('name'),
'age' => $request->input('age'),
'classroom_id' => 1
]
);
This is the correct way, rather than running your insert twice which is unnecessary.

Laravel Seeding Does not Fill in Fields

I have a database seed file:
class ContactTableSeeder extends Seeder {
public function run()
{
$contacts = array(
array(
'first_name' => 'Test',
'last_name' => 'Contact',
'email' => 'test.contact#emai.com',
'telephone_number' => '0111345685',
'address' => 'Address',
'city' => 'City',
'postcode' => 'postcode',
'position' => 'Director',
'account_id' => 1
)
);
foreach ($contacts as $contact) {
Contact::create($contact);
}
}
}
When I run php artisan migrate:refresh --seed it seeds the database and creates the relevant record in the contacts table, except that it does not fill the fields with any of the information in the seed array. I am using the exact same syntax for other tables and they work fine, and I've also checked each field thoroughly to make sure they match the database fields but no matter what I do it will not seed correctly.
Does anyone have any ideas?
I had this same problem but none of the above solutions worked for me. It turned out to be due to having a construct function in my model! After I removed this it worked fine!
public function __construct()
{
parent::__construct();
}
EDIT:
After further reading on this I discovered the issue is due to the fact that if you are going to include a constructor in your model must accept the attributes parameter and pass it to the parent. If you do this then the constructor does not break the DB seeding (and probably other things). I hope this saves someone else a headache.
public function __construct($attributes = array())
{
parent::__construct($attributes);
}
Turns out the issue was to do with relationships in my models.
For future visitors to this question: make sure to check all the functions in your models that define hasOne/hasMany/etc relationships. Read though the Eloquent docs for more.
Do you have $this->call("ContactTableSeeder") in your DatabaseSeeder class' run() function?
If you have ContactTableSeeder in it's own file, is the file named ContactTableSeeder.php exactly? If not it would fail to load according to the PSR-0 Standard.
These are my first thoughts.
Have you tried to replace the following lines:
foreach ($contacts as $contact) {
Contact::create($contact);
}
with
DB::table('contact')->insert($contacts);
assuming your table name is contact.
And also, make sure you have line like this
$this->call('ContactTableSeeder');
in your DatabaseSeeder class.

Resources