how to find column in table using laravel - php

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"]);

Related

How to sync if model id is hidden field?

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);

How to resolve null return in Laravel query?

Given my Models Person and Student. Now, one of my controller is doing this:
$person_id = \App\Models\Person::insertGetId(['name' => $request->name, ...]);
\App\Models\Student::create(['person_id' => $person_id, ...]);
$student = \App\Models\Student::where('person_id', $person_id)->first();
dd($student);
During execution, everything has been save but My problem is why i am receiving null on die and dump?
By the way, my student tables' primary and foreign key is the person_id column.
Edit
class Student extends Model
{
protected $fillable = ['section', 'current_year'];//there are other attribute here which I didn't show because I am using mobile
public function person(){
return $this->belongsTo('App\Models\Person', 'person_id', 'id');
}
...
}
Add person_id in $fillable property:
protected $fillable = ['section', 'current_year', 'person_id'];

How to retrieve all data from three tables according to groupby of second table's field value using Laravel eloquent query?

I have three models with some methods like
1.Employee Model
class Employee extends Model
{
protected $fillable = [
'employee_no','card_no','inactivedate', 'activedate', 'status',
];
public function office(){
return $this->hasOne(EmployeeOffice::class);
}
public function section(){
return $this->belongsTo('App\Hrm\Section');
}
}
2.EmployeeOffice Model
class EmployeeOffice extends Model
{
$fillable = ['employee_id','section_id','line_id','join_date','gross','confirm_date'];
public function employee(){
return $this->belongsTo(Employee::class);
}
public function section(){
return $this->belongsTo('App\Hrm\Section');
}
}
3.Section model....
class Section extends Model
{
protected $fillable = ['name','description','status'];
//
}
i need all inactive employee information according to the employee inactive date(from employee model) as well as their all office information from EmployeeOffice model and must be groupBy according to section_id which is (section_id as foreign key) available in EmployeeOffice model.
For that i have to go with some condition like ..
Employee::where('inactivedate','like','%'.$date.'%');
*And need all data from office and employee table
*need section name and grouped by as section name from section model
***please suggest me how can i solve this problem ***
Try this:
$data = Section::with(
array(
'employeeOffice' => function(
$query->with(
'employees' => function(
$query->where('employees.inactivatedate', 'like', '%'.$date.'%'
)
)
)
)
)
->get();
This should give you an array to every section_id. In this array are the employeeOffices (1:n-Relationship). The second query with with will fetch for each employeeOffice the employee who sits in it.
But if you defined the relationships right, this should do the trick to:
Section::with('EmployeeOffice.Employee')->get();
Nested Eager Loading
I have solved my problem by this...
if(Input::has('start') && Input::has('end')){
$start = Carbon::parse(Input::get('start'))->startOfDay();
$end = Carbon::parse(Input::get('end'))->endOfDay();
$start = $start->format('Y-m-d');
$end = $end->format('Y-m-d');
EmployeeOffice::query()->whereHas('employee',function ($query) use ($start,$end){
$query->whereBetween('inactivedate',[$start, $end])->where('status',0);
})->paginate()->groupBy('section_id');
}

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

Laravel 5 Model: Do not include certain columns in Eloquent

I am trying to find an easier approach to this simple function I have. Basically what I am doing is dynamically loaded a form that's based on an Eloquent model. I do not want to include certain columns in the model like id's and the created_at and update_at columns. I am able to accomplish this with the following piece of code:
get Controller:
$cms_information = collect(CmsUserInformation::where('users_id', Auth::user()->id)->first()->toArray());
$cms_information->forget('id');
$cms_information->forget('users_id');
$cms_information->forget('created_at');
$cms_information->forget('updated_at');
$cms_information->all();
return view('cms::admin.profile', ['user' => Auth::user(), 'cms_information' => $cms_information]);
Then, I will loop through the fields in a form and post them like so:
Post Controller:
$profile = CmsUserInformation::where('users_id', Auth::user()->id)->first();
$cms_user_information = Input::except('_token', 'email', 'password');
foreach($cms_user_information as $field => $info ) {
$profile->$field = $info;
}
$profile->save();
My Eloquent table:
id
user_id
first_name
last_name
email
created_at
updated_at
This works exactly how I want but I feel like it's a quick and dirty way around using the Eloquent object to accomplish this. Does anyone have a way to accomplish this same thing but only use Eloquent object rather than converting to an array and using the collect() function?
You can use the $hidden property on your Eloquent model:
class CmsUserInformation extends Model
{
protected $hidden = [
'id',
'users_id',
'created_at',
'updated_at',
];
}
This will automatically exclude the given attributes when the models are ultimately serialized.
If you only want to hide it in a specific instance, use the setHidden method:
$info = CmsUserInformation::where('users_id', Auth::id())->first();
$info->setHidden([
'id',
'users_id',
'created_at',
'updated_at',
]);
Use hidden property in the model you are using like this:
class User extends Model{
protected $hidden=[
'id',
'created_at',
'updated_at'
];
...
}

Categories