How to sync if model id is hidden field? - php

I'm trying to sync data to pivot table for my model. But my Recipe model has an hidden id field. Like this;
protected $hidden = ['id', 'content', 'difficulty_id'];
And when I try to sync relationships to pivot table, recipe_id becomes zero. If I remove id from $hidden above, it sync id without any problem. I also tried to call makeVisible("id") for the model but didn't help.
$changedMeals = $record->meals()->sync($meals);
How can I sync id when keeping it in $hidden?
Thank you very much...

currently, im using pivot with $hidden in primary, and foreign not in pivot, im using sync($request->field_to_sync) and im using validator to validate ids, and it worked
eg:
class Recipe ...
{
protected $hidden = ['id'];
public function meals(){
return $this->belongsToMany(Pivot::class);
}
}
class Meals ...
{
protected $hidden = ['id'];
public function recipe(){
return $this->belongsToMany(Pivot::class);
}
}
so i assume u are using sync() in your code without using Request::input(), you can try this :
$meals = Meals::select('id')->get()
->map(function($value, $key){
return $value->setVisible(['id']);
});
then u can use sync() like this :
Recipe::find(1)->meals()->sync($meals);

Related

how to find column in table using laravel

how to find other column in table using laravel. By using the find($id) i believe that this is for the id in the table. I want to find the lead_id column in table. How will i able to do that? Here is my code below
$recent = RecentlyViewed::findLeadId($leadId);
$status = "Close/Converted";
$recent->flag_status = $status;
$recent->save();
in my model
class RecentlyViewed extends Model
{
public static function findLeadId($leadId)
{
return static::where('lead_id', $leadId)->first();
}
//
protected $fillable = [
'lead_id',
'client_id',
'status',
'first_name',
'last_name',
'date',
'flag_status',
];
}
it wont work to get the lead_id in my table recently viewed table. Any help is muchly appreciated. TIA
Add protected $primaryKey = "lead_id"; in model. If primaryKey significant other impacts. The do with Laravel query builder.
Don't forget to add use DB;.
DB::table('RecentlyViewed')
->where('lead_id', $leadId)
->update(['flag_status' => "Close/Converted"]);

Retrieving error on one to many relationship laravel

Been learning laravel for 4 days and im trying to fix this error for 2 hours and i cant still fix it. I can save on one to many relationship but i cant retrieve data i think there something wrong with the relationship. Im trying to retrieve posts on user using this line but im getting not empty results on users but empty result on posts. Same thing happening on categories and posts which is many to many relationship but i cant save on many to many.
$users = User::with('posts')->get();
ANd im getting an error when i use this the error is
Undefined property: Illuminate\Database\Eloquent\Collection::posts()
$users = User::where('user_id','=','2')->get();
$posts = $users->posts()->get();
Heres my user Model
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $primarykey = 'user_id';
protected $table = 'users';
public function posts(){
return $this->hasMany("App\Post");
}
}
Heres my posts Model
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $primarykey = 'id';
protected $table = 'posts';
public function post_validation_rules(){
return [
'post_title' => 'required|min:5|unique:posts',
'post_body' => 'required'
];
}
public function user(){
return $this->belongsTo("App\User");
}
public function categories(){
return $this->belongsToMany('App\Category', 'category_id', 'category_id');
}
}
Categories Post
class Category extends Model
{
protected $primarykey = 'category_id';
protected $table = 'categories';
public function posts(){
return $this->belongsToMany('App\Post', 'post_id', 'id');
}
}
Database
Posts Table
id
user_id
post_title
post_body
createad_date
updated_date
Users Table
user_id
username
email
pass
createad_date
updated_date
You can only call relations on a single object, not on an entire collection. $users is a collection of User objects.
If you want a single user object, use the first() function to get the first User object that matches.
$user = User::where('user_id','=','2')->first();
$posts = $user->posts;
Update:
To get the posts directly in the user object, you need to use the with function:
$user = User::with('posts')->where('user_id','=','2')->first();
Try to declare the field that have the relation between your tables then, for example:
$this->hasMany(App\Post::class, 'user_id', 'user_id');
Laravel is searching for a field id in User table but it does not exist. so with this way you will tell it that the field you look is user_id

How to retrieve data from one to one relationship in Laravel 5.4

I have two MSSQL tables so i created two models [Adress] and [Webshop]. The foreign key is Adresse in both tables.
1.Model [Adress]
class Adress extends Model
{
protected $table = "Adress";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function webshop()
{
return $this->hasOne('App\Webshop', 'Adresse');
}
}
2.Model [WebShop]
class Webshop extends Model
{
protected $table = "Webshop";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function adress()
{
return $this->belongsTo('App\Adress','Adresse');
}
}
I would like to make a table with some data from the first and second table like the webshopID, mobile is in [Webshop] table and adress in the [Adress] table. I think this is a one to one relationship between this two tables.
in php artisan tinker:
App\Adress::all(); -> this is working
App\Adress::find(2910)->webshop -> this is also working
App\Adress::with('webshop')->get() -> this is NOT working
I would like to retrieve data from this two tables at the same time. Is this possible with a relationship or do i heave to use the joins?
EDIT:
maybe my foreignKeys are wrong
Adress table:
Webshop table:
Please try with this -
use App\Adress;
use App\Webshop;
$result = Webshop::with('Adress')->where('Webshop.id',$id)->get();
or
$result = Adress::with('Webshop')->where('Adress.id',$id)->get();
Hope this will help you.
Try to change your relationship in Address model to
$this->hasOne('App\Webshop', 'Adresse', 'Adresse');
and in Webshop model
$this->belongsTo('App\Address', 'Adresse', 'Adresse');
EDIT
Now to retrieve the relationships you can do
$webshop = App\Address::find($id)->webshop;
$address = App\Webshop::find($id)->address

Laravel: static::create vs DB:insert

If I use the following code snippet in my model it inserts the data:
$instance = DB::table('users')->insert(compact('email', 'username'));
But if I do this instead:
$instance = static::create(compact('email', 'username'));
It inserts null, but created_at and updated_at are inserted.
Laravel's created_at/updated_at are part of Illuminate\Database\Eloquent\Model. A raw DB::table query builder isn't an Eloquent model and thus doesn't have those automatic parameters.
NULL data is being inserted in the Eloquent query because Eloquent has a $fillable parameter you need to define. This parameter sets which columns can be mass-assigned. Laravel strips attributes not in this array when you do a fill, create, or otherwise instantiate a new object. In your model, you'd want:
class User extends Eloquent {
protected $fillable = ['email', 'username'];
}
ceejayoz answer is great, here's an explanation of how to call the model. Once the model is created, let's say this model:
class User extends Eloquent {
protected $fillable = ['email', 'username'];
}
Then you need to call by using the model directly and eloquents ORM like so:
// example is this. True method is TableName->ColumnName = Value;
$user = User::find($id);
$user->username = '';
$user->fullname = '';
$user->save();
The save will update the columns based on what you describe. With this you don't even need the fillable variable.
Some other variables for models that are good to know is:
protected $primaryKey = 'userid'; #if you have an primarykey that isn't named id
protected $table = 'tablename'; #if table name isn't pulling by the name of the model
protected $timestamps = true; #bool value, whether u have timestamp columns in table
You said us that you done
class User extends Eloquent {
protected $fillable = ['email', 'username'];
}
however in your comment you told us you got the following error in your apache log
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ''
for key 'users_email_unique' (SQL: insert into ``users
(updated_at, created_at``) values (2015-01-06 21:52:35, 2015-01-06 21:52:35))
Make sure to also include users_email_uniquein your fillable array if you want to set it.
class User extends Eloquent {
protected $fillable = ['email', 'username', 'users_email_unique'];
}

Laravel Removing Pivot data in many to many relationship

Not sure if I set this up correctly. In Laravel I'm creating two models with a many-to-may relationship
The models are Item and Tags. Each one contains a belongsTo to the other.
When I run a query like so:
Item::with('tags')->get();
It returns the collection of items, with each item containing a tags collection. However the each tag in the collection also contains pivot data which I don't need. Here it is in json format:
[{
"id":"49",
"slug":"test",
"order":"0","tags":[
{"id":"3","name":"Blah","pivot":{"item_id":"49","tag_id":"3"}},
{"id":"13","name":"Moo","pivot":{"item_id":"49","tag_id":"13"}}
]
}]
Is there anyway to prevent this data from getting at
you can just add the name of the field in the hidden part in your model like this:
protected $hidden = ['pivot'];
that's it , it works fine with me.
You have asked and you shall receive your answer. But first a few words to sum up the comment section. I personally don't know why you would want / need to do this. I understand if you want to hide it from the output but not selecting it from the DB really has no real benefit. Sure, less data will be transferred and the DB server has a tiny tiny bit less work to do, but you won't notice that in any way.
However it is possible. It's not very pretty though, since you have to override the belongsToMany class.
First, the new relation class:
class BelongsToManyPivotless extends BelongsToMany {
/**
* Hydrate the pivot table relationship on the models.
*
* #param array $models
* #return void
*/
protected function hydratePivotRelation(array $models)
{
// do nothing
}
/**
* Get the pivot columns for the relation.
*
* #return array
*/
protected function getAliasedPivotColumns()
{
return array();
}
}
As you can see this class is overriding two methods. hydratePivotRelation would normally create the pivot model and fill it with data. getAliasedPivotColumns would return an array of all columns to select from the pivot table.
Now we need to get this integrated into our model. I suggest you use a BaseModel class for this but it also works in the model directly.
class BaseModel extends Eloquent {
public function belongsToManyPivotless($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null){
if (is_null($relation))
{
$relation = $this->getBelongsToManyCaller();
}
$foreignKey = $foreignKey ?: $this->getForeignKey();
$instance = new $related;
$otherKey = $otherKey ?: $instance->getForeignKey();
if (is_null($table))
{
$table = $this->joiningTable($related);
}
$query = $instance->newQuery();
return new BelongsToManyPivotless($query, $this, $table, $foreignKey, $otherKey, $relation);
}
}
I edited the comments out for brevity but otherwise the method is just like belongsToMany from Illuminate\Database\Eloquent\Model. Of course except the relation class that gets created. Here we use our own BelongsToManyPivotless.
And finally, this is how you use it:
class Item extends BaseModel {
public function tags(){
return $this->belongsToManyPivotless('Tag');
}
}
If you want to remove pivot data then you can use as protected $hidden = ['pivot']; #Amine_Dev suggested, so i have used it but it was not working for me,
but the problem really was that i was using it in wrong model so i want to give more detail in it that where to use it, so you guys don't struggle with the problem which i have struggled.
So if you are fetching the data as :
Item::with('tags')->get();
then you have to assign pivot to hidden array like below
But keep in mind that you have to define it in Tag model not in Item model
class Tag extends Model {
protected $hidden = ['pivot'];
}
Two possible ways to do this
1. using makeHidden method on resulting model
$items = Item::with('tags')->get();
return $items->makeHidden(['pivot_col1', 'pivot_col2']...)
2. using array_column function of PHP
$items = Item::with('tags')->get()->toArray();
return array_column($items, 'tags');

Categories