retrieve data with where condition laravel 5.2 into controller - php

the question is how to get data from foreign key into my controller and pass to Session flash message view.
AbsenController#store
$this->validate($request, [
'siswa_id' => 'required',
'keterangan' => 'required',
]);
$alpaCount = Absen::where('siswa_id', '=', $request->siswa_id)
->where('keterangan', '=', 'Alpa')
->count();
if (Absen::where('siswa_id', '=', $request->siswa_id)
->whereRaw('DATE(created_at) = CURDATE()')
->exists()) {
return redirect()->back()->with('message', 'Data Telah Tersedia');
} elseif($alpaCount >= 3) {
$absen = new Absen;
$absen->siswa_id = $request->siswa_id;
$absen->keterangan = $request->keterangan;
$absen->save();
$nama = Siswa::where('id', '=', $request->siswa_id)->get();
Session::flash('warning', $nama->nama.' Sudah Lebih Dari 3 Kali
Alpa');
return redirect()->route('absen.index')
Look on $nama = Siswa::where('id', '=', $request->siswa_id)->get();
im trying to get data with $request->id and get the nama field and then pass to Session::flash('warning', $nama->nama.' Sudah Lebih Dari 3
Kali Alpa');
return redirect()->route('absen.index');
Absen#siswa
public function siswa()
{
return $this->belongsTo('App\Siswa');
}
Siswa#absen
public function absen()
{
return $this->hasMany('App\Absen');
}
maybe you can help me, Thanks
Absen Table
Siswa Table

find($request->id) i assume that $request->siswa_id because i can't find $request->id anywhere in your code
try this using Constraining Eager Loads
$nama = Absen::with(['siswa' => function ($query) use ($request) {
$query->where('id', $request->siswa_id);
}])->get();
Session::flash('warning', $nama->siswa->nama.' Sudah Lebih Dari 3
Kali Alpa');
EDIT ANSWERS
Based on table you shown in your question, it can be done like this
$namas = Absen::where('siswa',$request->siswa_id)->get(); //will return array because of absent as many siswa
foreach($namas as $nama) {
$siswa_name = $nama->siswa->nama;
}

You can load Absen with siswa, in where clause while filtering siswa_id, it binds to $request->siswa_id
$nama = Absen::with(['siswa' => function ($query) use($request) {
$query->where('siswa_id', $request->siswa_id;);
}])->get();
Also, you can lazy-eager load:
$name = Absen::find($request->id);
and then call load function to load related model.
$name->load('siswa');
Since siswa is an array. You can loop through that and find the desired object name. Or you can simply just take the first element by using first() function. e.g.
$nama->siswa->first()->anyproperty;

Related

Laravel Eloquent: How to add where condition from the with function model relation

Anyone can help me? How to add where condition from the with function model relation.
I tried ->where('driver.group_id',$group_id) but it does not work. please look my code below.
public function getDriversDailyEarnings()
{
$group_id = Auth::user()->group->id;
$today = Carbon::today();
$data = DailyEarnings::with(['payout_cost',
'status:id,name',
'driver' => function ($query) {
$query->with('user');
}])
->where('driver.group_id',$group_id)
->whereDate('created_at', $today)
->get();
return response()->json($data, 200);
}
You can try this. Haven't tested it yet.
DailyEarnings::with([
'payout_cost',
'status:id,name'
'driver' => function($query) {
$query->where('group_id', auth()->user()->group->id)->with('user');
}
])
->whereHas('driver', function($query) {
$query->where('group_id', auth()->user()->group->id);
})
->whereDate('created_at', now()->format('Y-m-d'))
->get();
To pass other clauses to a relation, just use it inside an array, where the key and the name of the relation and the value is a function that receives an instance of the query, something like this:
public function getDriversDailyEarnings()
{
$data = DailyEarnings::with([
'payout_cost' => function ($myWithQuery) {
$myWithQuery->where('column-of-relation-here', 'value-here')
->orWhere('name', 'LIKE', '%Steve%');;
}
])->get();
return response()->json($data, 200);
}
Perhaps something like this:
// ->where('driver.group_id',$group_id)
->whereHas('driver', fn($qry) => $qry->where('group_id', $group_id)) // if group_id a field on driver

Laravel | How to perform search with multiple attributes

I am creating property website and i am doing search with number of attributes, but the problem is that in search controller i have very large code and its very difficult to handle, is there any other solution exist in laravel?
$list_property = Listing_property::where([
['property_type', $request['property_type']],
['city', $request['city']],
['location', $request['location']],
['property_area_type', $request['property_area_type']],
['property_size', $request['property_size']],
['price', $min],
['price', $max]
])
->orderBy('updated_at', 'DESC')
->paginate(21);
The easiest way to search multiple column :
public function search(Request $request){
$query = $request->search;
$users = DB::table('users');
if($query){
$users = $users->where('name', 'LIKE', "%$query%");
}
if($request->city){
$users = $users->where('city',$request->city);
}
if($request->town){
$users = $users->where('town', $request->town);
}
if($request->unit){
$users = $users->where('unit', $request->unit);
}
$users->get();
return view('users.index')->with('users', $users);
}

Putting order by inside with(), in Laravel

I have a controller that filters the columns in it's table based on the variable received in the get query, then it returns it with another table's value based on the id of the variable gotten, But now for the $filter_by_name condition I want to filter by the first_name column in the users table, please how can i do that, i.e I want to return the users table ordered by their first_name column
DB-STRUCTURE
COMPANY-USERS TABLE
id company_id user_id role created modified active department_level
USERS TABLE
id
first_name
last_name
email
password
active_company
profile_photo_id
verified
active
remember_token
created
modified
Company-users Controller
public function getCompanyUsers($companyId)
{
$filter = strtolower(Input::get('filter'));
if($filter && $filter === 'on' ){
$filter_by_date = strtolower(Input::get('filter_by_date'));
$filter_by_name = strtolower(Input::get('filter_by_name'));
$filter_by_role = strtolower(Input::get('filter_by_role'));
if($filter_by_date){
if($filter_by_date == 'oldest'){
$users = CompanyUser::where('company_id', $companyId)->orderBy('created', 'DESC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}else{
$users = CompanyUser::where('company_id', $companyId)->orderBy('created', 'ASC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}
}elseif ($filter_by_name){
if($filter_by_name == 'ascending'){
$users = CompanyUser::where('company_id', $companyId)->orderBy('first_name', 'ASC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}else{
$users = CompanyUser::where('company_id', $companyId)->orderBy('first_name', 'DESC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}
}elseif($filter_by_role){
if($filter_by_role == 'member'){
$users = CompanyUser::where(['company_id' => $companyId,'role'=>'Member'])->with(['user','user.userDepartments','user.userDepartments.department'])->get();
// dd($users);
return $users;
}elseif($filter_by_role == 'manager'){
$users = CompanyUser::where(['company_id' => $companyId,'role'=>'Manager'])->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}else
$users = CompanyUser::where(['company_id' => $companyId,'role'=>'Admin'])->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}
}
$users = CompanyUser::where('company_id', $companyId)->
with(['user','user.userDepartments','user.userDepartments.department'])->get();
//dd($users);
return $users;
}
you can pass closer functions when eager loading to add constrains like that, see more on laravel docs:
$users = CompanyUser::with(['user'=> function ($query) {
$query->orderBy('first_name', 'desc');
}
])
->where('company_id', $companyId)
->get();
You have to do orderBy on a relational model like below:
$users = CompanyUser::where('company_id', $companyId)
->with(['user' => function($subQuery){
$subQuery->orderBy('first_name', 'ASC');
}])
->with(['user.userDepartments','user.userDepartments.department'])
->get();
return $users;
One way is to add column 'first_name' in the 'COMPANY-USERS' TABLE
And now you can do order by ('first_name','ASC').
I think its not the best way but no other idea comes in my head.

I cannot fetch data from using this code

public function orderView(Request $request){
$orderByID = $request->id;
$orderDetailsView = DB::table('order_details')
->where('order_id',$orderByID)
->get();
return view('admin.order.vieworder', ['orderDetailsView' => $orderDetailsView]);
}
If i return only $orderByID it shows the id. But using this id i cannot fetch data from the database table. it shows empty array.
Try this code
$orderss = DB::table('order_details')->where('order_id', '=', $orderByID)->get();

Selecting required fields using relations in Laravel

I have a model Meetings like this:
public function meeting_comments(){
return $this->hasMany('App\MeetingsComments', 'meeting_id', 'id');
}
public function meeting_users() {
return $this->hasMany('App\UserMeetingDetails', 'meeting_id', 'id');
}
The Controller is like this:
$res = Meetings::with('meeting_comments', 'meeting_users')
->select('')->get()->toArray();
I only need comments from meeting_comments and user_id from meeting_users.
What do I put in select to only get the required fields from meeting_comments and meeting_users ??
You do it through a closure in the with call:
$res = Meetings::with(['meeting_comments' => function($query) {
$query->select('comments', 'meeting_id');
}, 'meeting_users' => function($query) {
$query->select('user_id', 'meeting_id');
}])
->get()->toArray();
I'm taking this from memory, so the syntax may be slightly incorrect, but it should work. :)

Categories