Laravel, how to get selected, db fields - laravel

Have a model, from controller, I need access this Model db fields.
Code in controller:
$crud -> get() -> getAttributes();
//$crud->attributesToArray()
print_r($crud);
I was able to get entire table fields, but I need only fields, which are selected. Need dynamically show table with selected fields only, which can change during run time.

Assume you have a query:
$query = Crud::select('id as Id', 'name as Name', 'something')
->selectRaw('CONCAT(id, "-", name) as Serial')
->get();
Without knowing what the query is, to get a table that looks like this
Id
Name
something
Serial
1
A
lorem
1-A
..
....
.........
......
You need to use the Builder instance (before calling ->get()
$query = Crud::select('id as Id', 'name as Name', 'something')
->selectRaw('CONCAT(id, "-", name) as Serial');
$results = $query->get();
dump($query->getQuery()->columns);
/*
[
'id as Id',
'name as Name',
'something',
Illuminate\Database\Query\Expression
]
*/
dump(array_map(function ($column) {
return $column instanceof Illuminate\Database\Query\Expression
? Str::afterLast($column->getValue(), 'as ')
: Str::afterLast($column, 'as ');
}, $query->getQuery()->columns));
/*
[
'Id',
'Name',
'something',
'Serial'
]
*/
So you could that to a view.
$query = Crud::select('id as Id', 'name as Name', 'something')
->selectRaw('CONCAT(id, "-", name) as Serial')
->get();
$columns = array_map(function ($column) {
return $column instanceof Illuminate\Database\Query\Expression
? Str::afterLast($column->getValue(), 'as ')
: Str::afterLast($column, 'as ');
}, $query->getQuery()->columns);
$results = $query->get();
return view('view', compact('columns', 'results'));
And then in your view
<table>
<thead>
<tr>
#foreach ($columns as $column)
<th>{{ $column }}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach ($results as $result)
<tr>
#foreach ($columns as $column)
<td>{{ $result->{$column} }}</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>

I'm not sure what you mean by 'selected' database fields. If this is a list of column names coming from a form, you can simply pass that to the get() method:
$crud->get([
'id',
'name',
'created_at',
]);
If instead you want a list of the available columns, you can't get that from the model itself (it is unaware of which columns exist). Instead you can use:
$table = (new Crud)->getTable();
$columns = DB::getSchemaBuilder()->getColumnListing($table);

You can use two methods, get() or all()
$crud -> get(['column1', 'column2'])
$crud -> all(['column1', 'column2'])

Related

Laravel 9 Calling oldestOfMany() in Controller from Model

I have a Customer model and Customer hasMany Xray_machines. I am trying to select the oldest cert_date from the xray_machines table to populate a table in the view that lists the customer_name and the oldest cert_date. I found oldestOfMany() and it seems to be a good option but it is displaying the first cert_date rather than the oldest.
Customer Model
public function xray_machine()
{
return $this->hasMany(Xray_machine::class);
}
public function oldestCert(){
return $this->hasOne(Xray_machine::class)->oldestOfMany('cert_date','min');
}
Controller
public function xray_unscheduled(){
$due = Carbon::now()->addMonth(3)->endOfMonth()->toDateTimeString();
$customers = Customer::whereHas('Xray_machine', function ($query) use($due) {
$query->where('cert_date','<=', $due);
})
->whereNull('xray_scheduled')->orWhere('xray_scheduled','<>','')
->oldestCert()
->orderBy(
Xray_machine::select('cert_date')
->whereColumn('xray_machines.customer_id','customers.id')
->take(1),'asc'
)
->get()->all();
return view('work_orders/xray_unscheduled', compact('customers'));
}
View
#foreach ($customers as $customer)
<tr>
<td>
{{ $customer->customer_name}}
</td>
<td>
{{ \Carbon\Carbon::parse($customer->oldestCert()->cert_date)->format('Y-m-d')}}
</td>
</tr>
#endforeach

How to pass data from controller to view in Laravel

Please help me. I have these 3 tables, and I have problems on how to call the category name based on the restaurant id from Controller to view. Thank you in advance.
Table items
Table categories
Table restorant
This is my Controller
public function index()
{
if (auth()->user()->hasRole('owner')) {
$items = Items::with('category')->get();
$restorant_id = auth()->user()->restorant->id;
$category = Categories::where(['restorant_id' => $restorant_id]);
}
return view('point-of-sale::index', [
'category' => $category,
'items' => $items,
]);
}
If you add get() to the end of your $category = Categories::where(['restorant_id' => $restorant_id]); statement, you'll have an Eloquent collection returned:
$category = Categories::where(['restorant_id' => $restorant_id])->get();
Pass the $category variable to your view as you are currently, consider renaming it to $categories though just to infer that there could be multiple.
Then in your view you can loop over the Category results and access the name property:
#forelse ($category as $cat)
{{ $cat->name }}
#empty
No categories.
#endforelse
Update
If you want to get items by their category_id, you can either do as you have done with $categories:
$items = Items::where(['category_id' => $category_id])->get();
Alternatively, if you have an items relationship on your Categories model you can access them that way:
$category = Categories::with('items')
->where(['restorant_id' => $restorant_id])
->get();
The above will eager load the items related to a category which you can then access in your view, for example:
#forelse ($category as $cat)
{{ $cat->name }}
#foreach ($cat->items as $item)
{{ $item->name }}
#endforeach
#empty
No categories.
#endforelse

How to joining Table in Laravel 5.8

I have 2 table users and data .
in users table have :
id | name |email | etc
in data table have :
id | user_id | no_data | etc
i create model Data like this
public function users()
{
return $this->HasMany(\App\User::class ,'id');
}
my Controller :
public function pns()
{
$data = Data::get();
//DB::table('data')
//->join('users','data.user_id','=','users.id')
//->where(['user' => 'something', 'otherThing' =>
// 'otherThing'])
//->get(); // i trying to join this table but still error
return view('admin.data',['data' => $data]);
}
now i want to show view data in table :
on my view blade :
<th>No </th>
<th>id </th>
<th>Name </th>
<th>email </th>
#php
$no=0;
#endphp
#foreach ($data as $i)
<tr>
<td class=" ">{{ ++$no }}</td>
<td class=" ">{{ $i->user_id}}</td>
<td class=" ">{{ $i->users->name}}</td>
<td class=" ">{{ $i->email}}</td>
</tr>
this user_id is showed ,but this 'name' is cant showed and get error :
Property [name] does not exist on this collection instance.
edited my dd($data)
#attributes: array:18 [▼
"id" => 1
"user_id" => 6
"email" => 'q#gmail.com'
//etc
"created_at" => "2019-06-18 17:27:54"
"updated_at" => "2019-06-18 17:27:54"
]
Assuming, your one user can have multiple data. Here is my solution
For User Modal
class User extends Authenticatable
{
<YOUR OTHER CODES HERE>
public function datas(){
return $this->hasMany(Data::class,'user_id','id');
}
}
For Data.php [ Data modal]
class Data extends Model{
<YOUR OTHER CODE>
public function userDetail(){
return $this->belongsTo(User::class,'user_id','id');
}
}
From your controller:
$data = Data:with('userDetail')->get();
echo '<pre>';
print_r($data->toArray()); // This will give you an array of data with user details.
do this $data = Data::with('users')->get();
Use this Query
DB::table('data')
->join('users','data.user_id','=','users.id')
->where('user_id','=',1)
// Here you can also add more wheres
// But make sure where column exists in one of queried table i.e in
// users | data
->select([
'no',
'user_id as id',
'name',
'email'
])
->get(); // i trying to join this table but still error
You need to update your relationship in data model
public function users()
{
return $this->hasMany(\App\User::class ,'user_id');
}
it should be hasMany not HasMany and user_id not id
Then use this: $data = Data::with('users')->get();
use hasOne in your User model
public function data()
{
return $this->hasOne('App\Data', 'user_id');
}
//controller
return view('admin.data')->with($data);

Laravel - Using Where Clause with If Statement and Parameter

I have a Laravel Query with where clause statement and a parameter in it. The $plan coming from the source is string and the values are:
Daily, Weekly, Monthly, Wallet
but the value of $plan in the destination, users table ($users) are:
1,2,3,4
Parameter Source:
#foreach($billings as $key => $billing)
<tr>
<td>{{ ++$key }}</td>
<td><a class="btn btn-info" href="{{ route('revenueDetail',$billing->plan) }}">{{ $billing->plan }}</a></td>
<td>{{ $billing->total_plans }}</td>
<td>{{ $billing->total_amount }}</td>
</tr>
#endforeach
<tr>
<td colspan="8">
{{ $billings->links() }}
</td>
</tr>
Controller: Query
public function revenueDetail($plan = null)
{
$revenuedetails = DB::table("users")
->select(
"users.username",
DB::raw("DATE(users.created_at) as subscription_date")
)
->where('users.plan', $plan)
->get();
}
What I want to achieve is that, in the where clause in revenueDetail() function, if:
$plan = Daily then users.plan = 1
$plan = Weekly then users.plan = 2
$plan = Monthly then users.plan = 3
$plan = Wallet then users.plan = 4
How do I achieve this?
Based on last sentences, i assume you need to map Daily string which == 1
protected static $type = [
'Daily' => 1,
'Weekly' => 2,
'Montly' => 3,
]
then
public function revenueDetail($plan = null)
{
$revenuedetails = DB::table("users")
->select("users.username", DB::raw("DATE(users.created_at) as subscription_date"))
->where('users.plan', self::$type[$plan] ?? null) // ?? will escape exception if $plan is null
->get();
}
From view user should send id instead of value. However if u want to send value you should ask plans table for id of value u send. I recommend to store plans in cache. Another solution is to make class with Constans like your plans (if u dont want to extend it in the future)

Select query with relationship laravel one to many

I have a relational mode like this:
Model Siswa
public function kelengkapan()
{
return $this->belongsTo('Modules\PesertaDidik\Entities\SiswaKelengkapan');
}
Model SiswaKelengkapan
public function siswas()
{
return $this->hasMany('Modules\PesertaDidik\Entities\Siswa');
}
I want to use select query with relational
in this controller:
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
this is my blade...
<td>{{$data->kelengkapan->kelas_masuk}}</td>
but an error in the blade like this
Trying to get property 'kelas_masuk' of non-object
I want to show kelas_masuk in the table,
How to use the select query with relation eloquent?
There is no issue with your select query
You are trying to retrieve the data on null that's why you get Trying to get property 'kelas_masuk' of non-object
Controller
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
Blade file
Assume you are using foreach or forloop
<td>{{ $data->kelengkapan->kelas_masuk ?? '--' }}</td> //coalescing operator
Or
<td>
#if(!is_null($data->kelengkapan))
{{ $data->kelengkapan->kelas_masuk }}
#endif
</td>
Here you are used get() method so it's return all the rows
$siswa = Siswa::select('nama', 'nisn', 'tempat_lahir', 'tanggal_lahir', 'jk')->with('kelengkapan')->get();
return view('pesertadidik::crud.index', compact('siswa'));
in your blade
<td>{{$siswa[0]->kelengkapan->kelas_masuk}}</td>
You can also use foreach loop.
#foreach($siswa as $data)
<tr>
<td>{{$data->kelengkapan->kelas_masuk}}</td>
</tr>
#endforeach

Resources