Laravel5 Eloquent model not hiding json values - json

My contacts model is not hiding fields. This worked in Laravel4 with no problems, so did something change? am i doing it wrong?
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $table = 'users';
protected $hidden = ['confirmation_code', 'confirmed', 'status'];
protected $dates = ['deleted_at'];
}
I have even tried the reverse by only allowing certain fields
protected $visible = ['lName', 'fName', 'company', 'phone']
Could the problem be that my Contacts model is using the same table as my Users model? If thats the case. Whats the right way to have 2 models use the same table?

I missed the fact that i had 2 different contact models... in different namespaces.. I was referencing the wrong namespace. So everything is working like it should. It was all me not paying attention.

Related

Query builder don't accept onlyTrashed()

I'm a beginner and cant find a solution to my problem. I trying to get "onlyTrashed" from my DB but Laravel 8 don't accept my query commands :( I tried many scenarios but unsuccessful.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Category;
class CategoryController extends Controller{
public function AllCat(){
$categories = $trashCat = DB::table('categories')
->join('users','categories.user_id','users.id')
->select('categories.*','users.name')
->latest()
->paginate(5);
//$categories = Category::latest()->paginate(5);
// $trashCat = Category::onlyTrashed()->latest()->paginate(3);
return view('admin.category.index', compact('trashCat','categories'));
public function SoftDelete($id){
$delete = Category::find($id);`enter code here`
return Redirect()->back()->wiht('success',' Category Delete Successfuly');
Route::get('/softdelete/category/{id}', [CategoryController::class,'SoftDelete']);
Please make sure that your model imports and uses SoftDeletes trait to implement soft delete in your model and make sure that your table has deleted_at field, your model may look like below codes.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Category extends Model
{
use SoftDeletes;
And in your SoftDelete function within the controller, I think you miss delete() function, your function should look like:
public function SoftDelete($id) {
$delete = Category::find($id)->delete();
return redirect()->back()->with('success',' Category Delete Successfully');
}
Once you implement SoftDeletes trait into your model, delete() function should mark deleted by filling the deleted_at with timestamp or DateTime automatically. Once you implement the above codes, onlyTrashed() should work.
$categories = Category::latest()->paginate(5);
$trashCat = Category::onlyTrashed()->latest()->paginate(3);

database relation between two different server

I have two servers and both of them contain several tables. Many of them contain relations. Now I need to join those tables and fetch data. I have no clue how to write this sort of query. Currently, I'm working in Laravel. Any suggestions will help me.
Thanks in advance.
If you want to use model relationships you can add connection and table field in your model;
class User extends Model {
public $connection = 'firstconnection';
public $table = 'users';
...
public function comments() {
return $this->hasMany(Comment::class);
}
}
class Comment extends Model {
public $connection = 'secondconnection';
public $table = 'comments';
...
}
You can define connections in your config/database.php, default connection is mysql.
If you write raw queries you can use full table path (specify database):
SELECT * FROM db1.users JOIN db2.comments ON db1.users.id = db2.comments.user_id;
Note: you must have enough privileges on both tables to join and select data. If you use exists, has or semething like that where ORM needs to join two table.
Hope this helps you

Yii2 relation based on attribute values instead of keys

I have 2 tables in the db (mysql), and between the 2 there is no classic relationship through keys or ids. The only way I could define relationship would be through attribute values. E.g. table wheel and car and certain wheels would match certain cars because of the size only. Can it be defined on DB level, and/or in yii2, and if yes, how?
In the relations I can add an onCondition(), but you have to define an attribute (???), too:
public function getWheels() {
return $this->hasMany(\app\models\Wheel::className(), ['???' => '???'])->onCondition(['<', 'wheelsize', $this->wheelsize]);
}
I could use a fake attribute and set it in all records like to 1, but it seems a little bit odd for me.
I find nothing on the web regarding this or maybe I'm just searching the wrong way, or maybe I'm trying something that's totally bad practice. Can you please point me to the right direction?
Hypothetically you can set an empty array as a link, but for security reasons (I think) the condition "0 = 1" is automatically added in the select.
I faced your own problem several times and the best solution I could find was to use ActiveQuery explicitly (similar to what happens for hasOne and hasMany):
public function getWheels() {
return new ActiveQuery(\app\models\Wheel::className(), [
'where' => 'my condition' // <--- inserte here your condition as string or array
'multiple' => true // true=hasMany, false=hasOne
// you can also add other configuration params (select, on condition, order by, ...
]);
}
This way you can get both the array and the ActiveQuery to add other conditions:
var_dump($model->wheels); // array of wheels objects
var_dump($model->getWheels()); // yii\db\ActiveQuery object
$model->getWheels()->andWhere(...); // customize active query
I don't think that you could achieve this through relation.
But there is a way to work around the limitation.
<?php
namespace app\models;
class Car extend \yii\db\ActiveRecord
{
/**
* #var \app\models\Wheel
*/
private $_wheels;
/**
* #return \app\models\Wheel[]
*/
public function getWheels()
{
if (!$this->_wheels) {
$this->_wheels = Wheel::find()
->where(['<', 'wheelsize', $this->wheelsize])
//->andWhere() customize your where here
->all();
}
return $this->_wheels;
}
}
Then you could access the wheels attribute just as relation does.
<?php
$car = Car::find(1);
$car->wheels;
Beware that this way does not support Eager Loading

MySQL/Eloquent belongsToMany relation - two tables same pivot table allowed?

Is it allowed to have two tables, each with a belongsToMany() relation to each other, using the same pivot table?
Here is my User table:
And here is my Org table:
And here is the pivot table:
Here is the Eloquent User.php model:
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
protected $table = 'users';
public $timestamps = true;
use Authenticatable;
use SoftDeletes;
protected $dates = ['deleted_at'];
public function orgs()
{
return $this->belongsToMany('App\Org', 'org_user', 'org_id', 'user_id')->withPivot('role_id');
}
}
And here is the Eloquent Org.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Org extends Model {
protected $table = 'orgs';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
public function users()
{
return $this->belongsToMany('App\User', 'org_user', 'org_id, user_id')->withPivot('role_id');
}
}
Is it OK to do this? (i.e. use a shared pivot table) Does anyone with experience foresee any issues here? Or maybe someone could comment on standard practice/share some insights?
Absolutely you can! This is the beauty of a many to many relationship, in fact the example at http://laravel.com/docs/4.2/eloquent#many-to-many has the User and Role classes both set with belongsToMany. Thought being in that case (and sounds like in yours as well) that a user can have multiple roles and each role can be associated with multiple users.
Regarding your last two questions, the only part that gave me pause is the use of a role_id within the pivot table. The code you provided doesn't go into detail on what purpose that serves. As long as the User would only ever have one role associated with an Org this is fine, but if it could ever be more than one I would recommend another table to hold that User to Org role relationship.

kohana add column to inherit model

I was wondering how to work with kohana orm and inheritances.
Supose I have a model called Vehicle
$_table_columns with 5 columns
The lets supose I create another model called Car and I want to add 5 more columns to the model. How should I modify the parent $_table_columns variable or should I override it?
Thanks
I suppose you're looking for something like this protected $_table_columns = parent::_table_columns + array(...);. Unfortunatly PHP won't allow for this, so you will have to either override $_table_columns and list all 10 columns or override ORM reload_columns method like this:
public function reload_columns($force = FALSE)
{
$this->_table_columns = parent::_table_columns + array(...);
parent::reload_columns($force);
}