I got one variable in controller ($id), I want to pass it to the model:
CONTROLLER:
public function user_load_more($id, $friendly_url)
{
$user = User::where('friendly_url', '=', $friendly_url)
->with('shares_load_more.links.tag', 'userProfile.get_following')
->with(['shares_load_more.links.page' => function ($query) {
$query->select('id', 'name', 'friendly_url');
}])->orderBy('id', 'desc')->first();
return view("site.list.user.links", compact("user"));
}
MODEL (User.php): (?)
public function shares_load_more($id) //--- put the id here?
{
return $this->hasMany(Share::class, 'user_id', 'id')
->select('id', 'link_id', 'user_id', 'shared_in', 'content', 'created_at')
->take(2)
->orderBy('id', 'desc')
->where('id', '<', $id)
->where('type', '=', 0);
}
You don't really need to pass variable in a model, there is an alternate method to do it.
public function user_load_more($id, $friendly_url)
{
$user = User::where('friendly_url', '=', $friendly_url)
->with('shares_load_more.links.tag', 'userProfile.get_following')
->with(['shares_load_more' => function($query) use($id) {
$query->where('id', '<', $id);
}, 'shares_load_more.links.page' => function ($query) {
$query->select('id', 'name', 'friendly_url');
}])->orderBy('id', 'desc')->first();
return view("site.list.user.links", compact("user"));
}
Model:
public function shares_load_more($id) //--- put the id here?
{
return $this->hasMany(Share::class, 'user_id', 'id')
->select('id', 'link_id', 'user_id', 'shared_in', 'content', 'created_at')
->take(2)
->orderBy('id', 'desc')
->where('type', '=', 0);
}
It will append to the relation query
Related
Here is my query:
$fix = Fixture::select('fixtures.*')
->whereDate('kickoff', '<', $date)
->with('competition')
->with('teamA')
->with(['teamA.standing' => function ($q) {
$q->whereColumn('standings.competition_id', '=', {{here i want the competition_id from competitions or fixtures table}} );
}])
->with('teamB')
->with(['teamB.standing' => function ($q) {
$q->whereColumn('standings.competition_id', '=', {{here i want the competition_id from competitions table or fixtures table}});
}])->get();
Code from Fixture model:
public function teamA()
{
return $this->belongsTo(Team::class,'team_a','id');;
}
public function teamB()
{
return $this->belongsTo(Team::class,'team_b','id');;
}
Code from Team model:
public function standing()
{
return $this->hasOne(Standing::class);;
}
Code from Standing model:
public function team(){
return $this->belongsTo(Team::class);
}
public function competition()
{
return $this->belongsTo(Competition::class);
}
Can someone help me to get this done or if I am doing it wrong what's the correct way?
->with(['teamA.standing' => function ($q) {
$q->whereColumn('standings.competition_id', '=', {{here i want the competition_id from competition table or fixtures table}} );
}])
Example:
Category::select('id', 'name')->whereHas('statuses', function($query) { $query(); })->with('courses')->get();
I have Category Model that has one to many relation with itself.
It means each category has many children and each child has many products.
Now, I want to show parent categories (it means parent_id is null) with all products (list of products of all children).
Each product has category_id that category is child.
What is the best way to handle this in Laravel resources?
Category Model
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Models\Products', 'category_id', 'id');
}
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id', 'id');
}
}
My Query:
$categories = Category::select(['id', 'name'])
->where('parent_id', '=', null)
->with(['children' => function ($query){
$query->select(['id']);
$query->with('products:id,title,description,banner');
}])
->orderBy('id', 'desc')
->get();
And Resource:
public function toArray($request)
{
return [
'id' => $this->id,
'category' => $this->name,
'products' => [],
];
}
I tried many different ways to show products, none of them has worked so far.
I used hasManyThrough relation to get all product of each main category
Relation function:
public function childrenproducts() {
return $this->hasManyThrough( Product::class, Category::class , 'parent_id', 'category_id' );
}
Query:
$categories = Category::select(['id', 'name'])
->where('parent_id', '=', null)
->has('childrenproducts', '>=', 1)
->with(['childrenproducts' => function ($query) {
$query->select(['products.id', 'products.title', 'products.description', 'products.banner']);
$query->orderBy('products.id', 'desc');
}])
->orderBy('id', 'desc')
->get();
Resource:
public function toArray($request)
{
return [
'id' => $this->id,
'category' => $this->getName(),
'products' => ProductResource::collection($this->whenLoaded('childrenproducts'))
];
}
I am using Laravel-5.8 to get the count of employees that have applied for leave and those that have not applied for a particular year.
I have these 3 tables: hr_employees, hr_departments and hr_leave_requests.
class HrDepartment extends Model
{
protected $table = 'hr_departments';
protected $fillable = [
'id',
'company_id',
'dept_name',
];
}
class HrEmployee extends Model
{
protected $table = 'hr_employees';
protected $fillable = [
'id',
'company_id',
'first_name',
'last_name',
'department_id',
];
public function department()
{
return $this->belongsTo('App\Models\Hr\HrDepartment', 'department_id', 'id');
}
}
class HrLeaveRequest extends Model
{
protected $table = 'hr_leave_requests';
protected $fillable = [
'id',
'company_id',
'leave_status',
'employee_id',
];
public function department()
{
return $this->belongsTo('App\Models\Hr\HrDepartment', 'department_id', 'id');
}
}
An employee can apply for a leave several times in a year, but it will be counted as one. A department has many employees. Here is my code below:
$leaveReports = DB::table('hr_departments AS d')
->leftJoin('hr_employees AS e', function ($join) use ($userCompany) {
$join->on('d.id', '=', 'e.department_id')
->where('e.company_id', '=', $userCompany)
->where('e.hr_status', '=', '0');
})
->join('hr_leave_requests AS lr', function ($join) use ($userCompany) {
$join->on('e.id', '=', 'lr.employee_id')
->where('lr.company_id', '=', $userCompany)
->where('lr.leave_status', '!=', '0');
})
->where('d.company_id', '=', $userCompany)
->select(
'd.dept_name',
DB::raw('COUNT("lr.id") as applied_count'),
)
->groupby('lr.employee_id')
->get();
I want to display the result below:
I want to list all the departments, count the number of employees that have applied for leave and those that have not. if leave_status is not 0, then employee_id has applied for leave. To get applied in a department, subtract total applied in that department from total employee in that department.
If I have 3 departments and 50 employees. It shows all the departments and show the count those that have applied and those not not applied per department
However, instead of get the type of result in the diagram, it calculated all the employees as total applied.
How do I resolve this?
Thanks
Option 1: Eloquent Relationships.
You could do it by using the withCount method. But for that you need to first define the relationships in your HrDepartment model.
class HrDepartment extends Model
{
protected $table = 'hr_departments';
protected $fillable = [
'id',
'company_id',
'dept_name',
];
public function employees()
{
return $this->hasMany('App\Models\HrEmployee', 'department_id', 'id');
}
public function leave_requests()
{
return $this->hasManyThrough('App\Models\HrLeaveRequest', 'App\Models\HrEmployee', 'department_id', 'employee_id');
}
}
$departments = HrDepartment::select('hr_departments.dept_name')
->withCount([
'leave_requests as total_applied' => function ($query) {
$query->where('hr_leave_requests.leave_status', '=', 0);
},
'leave_requests as total_not_applied' => function ($query) {
$query->where('hr_leave_requests.leave_status', '!=', 0);
},
])
->where('hr_departments.company', '=', $userCompany)
->get();
Option 2: Query Builder
You can get the same result by copying and pasting the query eloquent makes in the base query builder but it doesn't really look pretty in comparison.
$departments = DB::table('hr_departments as d')
->select([
'd.dept_name',
'total_applied' => function ($query) {
$query->from('hr_leave_requests as lr')
->join('hr_employees as e', 'e.id', 'lr.employee_id')
->selectRaw('count(*)')
->whereColumn('d.id', 'e.department_id')
->where('lr.leave_status', '=', 0);
},
'total_not_applied' => function ($query) {
$query->from('hr_leave_requests as lr')
->join('hr_employees as e', 'e.id', 'lr.employee_id')
->selectRaw('count(*)')
->whereColumn('d.id', 'e.department_id')
->where('lr.leave_status', '!=', 0);
}
])
->where('d.company', '=', $userCompany)
->get();
I have a problem with my function index() concerning a request. In fact, I have to adapt my old function with a recent.
For information, my function index() (old) below was written like this and it works !!
public function index(Request $req)
{
if ($req->search == "") {
$retours = Retour::join('eleves', 'retours.fk_eleve', '=', 'eleves.id')->orderBy('eleves.nom', 'asc')->select('retours.*')->paginate(5);
return view('admin.retours.index', compact('retours'));
} else {
$validated = $req->validate([
'search' => 'alpha',
]);
$retours = Retour::join('eleves', 'retours.fk_eleve', '=', 'eleves.id')->where('eleves.nom','like', '%' . $req->search . '%')->orderBy('eleves.nom', 'asc')->select('retours.*')->paginate(5);
return view('admin.retours.index', compact('retours'));
}
}
Now, I have to change a party of code and I must to adapt my request:
$retours = Retour::join('eleves', 'retours.fk_eleve', '=', 'eleves.id')->where('eleves.nom','like', '%' . $req->search . '%')->orderBy('eleves.nom', 'asc')->select('retours.*')->paginate(5);
Here is an idea of my new code, my problem is that the search bar doesn't filter ? ^^
public function index(Request $request)
{
$user = $request->user();
$retours = Retour::query()
->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
$query->where('email', $user->email);
})
->when($request->has('search'), function (Builder $query) use ($request) {
$query->join('eleves', 'retours.fk_eleve', '=', 'eleves.id')->orderBy('eleves.nom', 'asc')->select('retours.*');
})
->paginate(5);
return view('admin.retours.index', compact('retours'))
->with('display_search', $user->hasRole('admin'));
}
My problem is perhaps here ?
->when($request->has('search'), function (Builder $query) use ($request) {
$query->join('eleves', 'retours.fk_eleve', '=', 'eleves.id')->orderBy('eleves.nom', 'asc')->select('retours.*');
})
->paginate(5);
Do have you an idea please?
Thank you
I am trying to do a search on products but it does not return any results. I suspect it has something to do with the whereHas function but I just cannot figure it out. Here is my code:
My Relations:
Categories Model:
class Categories extends Eloquent {
public function product()
{
return $this->hasMany('Products')->orderBy('name');
}
}
Products Model:
class Products extends Eloquent {
public function category()
{
return $this->belongsTo('Category')->orderBy('name');
}
}
My search function:
public function search()
{
$search = Input::get('search');
$result = Products::where('name', 'LIKE', '%'. $search .'%')->get();
if ($result->first()) {
return View::make('groceries.index')
->with('categories', Categories::with('product')->orderBy('name', 'asc')
->whereHas('product', function($query) use ($search)
{
$query->where('name', 'LIKE', '%'.$search.'%');
}));
}
}
In the view:
#foreach ($categories as $category)
//do stuff
#foreach ($category->product as $products)
//Show results
#endforeach
#endforeach
You have to call get() to get the data.
And I think this will be more readable code.
public function search()
{
$search = Input::get('search');
$result = Products::where('name', 'LIKE', '%'. $search .'%')->get();
if ($result->first()) {
$categories = Categories::with('product')->orderBy('name', 'asc')
->whereHas('product', function($query) use ($search){
$query->where('name', 'LIKE', '%'.$search.'%');
})->get();
return View::make('groceries.index')
->with('categories', $categories);
}
}