i need help for Laravel 4.2
the models are:
//1. model kelengkapan
class Kelengkapan extends Eloquent{
public function detilKelengkapan(){
return $this->hasMany('DetilKelengkapan', 'id_kelengkapan');
}
}
// 2. model DetilKelengkapan
class DetilKelengkapan extends Eloquent{
public function tDetilKelengkapanPaket(){
return $this->hasMany('TDetilKelengkapanPaket', 'id_detil_kelengkapan');
}
public function kelengkapan(){
return $this->belongsTo('Kelengkapan', 'id_kelengkapan');
}
}
// 3. model TDetilKelengkapanPaket
class TDetilKelengkapanPaket extends Eloquent{
public function detilKelengkapan(){
return $this->belongsTo('DetilKelengkapan', 'id_detil_kelengkapan');
}
}
the controller is:
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
$q->where('id_paket', $paket);
})->get();
but the result has not filtering by "id_paket" but showed all data. thanks. (newbie)
Your Code:
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
$q->where('id_paket', $paket);
})->get();
The correct Code:
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
//the function should return the $q variable.
return $q->where('id_paket', $id);
})->get();
Explanation:
whereHas function has 2 compulsory arguments. A relationship function name, and a closure. The closure must return a query object so that filters can be chained.
Source: http://laravel.com/docs/4.2/eloquent#querying-relations
In there whereHas function you pass $id variable in the closure but you are using $packet inside.
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
$q->where('id_paket', $id);
//---------------------^
})->get();
Try it and let me know the result.
Related
in my controller parameter passed to posts function in user model with construct method .
class MyController extends Controller
{
private $user;
public function __construct(User $getuser)
{
$this->user = $getuser;
}
public function index($id = 2)
{
$posts = $this->user->posts($id);
$user = User::FindOrFail($id);
return $user->posts;
}
}
in my user model parameter accessed and passed to relationship .
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
function posts($id)
{
return $this->hasMany('App\Post')->where('id',$id);
}
}
it works when use like this
"return $this->hasMany('App\Post')->where('id',1);"
but not working with passed parameter. getting this error
"Symfony\Component\Debug\Exception\FatalThrowableError Too few
arguments to function App\User::posts(), 0 passed in
C:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php
on line 415 and exactly 1 expected"
Check your controller method you should be returning. ie: return $posts instead of return $user->posts as this is seeking to find posts without passing in the id as you do with $posts = $this->user->posts($id);
That's why you are getting a symphony error of too few arguments as you pass no arguments in return $user->posts
User Model
function posts($id)
{
return $this->hasMany('App\Post');
}
You could access the post with the given condition by using where on the relation method.
Querying relations
https://laravel.com/docs/7.x/eloquent-relationships#querying-relations
$post = $user->posts()->where('id', $id)->first();
You could use get() or first() according to your requirement.
$posts = $user->posts()->where('id', $id)->get();
If you want a user who has a post that satisfies the criteria.
$user = User::whereHas('posts', function($query) use($id){
$query->where('id', $id);
// You may add several other conditions as well.
})
->with(['posts' => function($query) use($id){
$query->where('id', $id);
}
])
->first();
Now,
$user->posts
will give a collection of only ONE post Model Instance that satisfied the condition
I put logic from my function index() of UserController in trait taht i created:
public function index()
{
$this->authorize('view', Auth::user());
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return UserResource::collection($users);
}
and this is my trait :
<?php
namespace App\Http\Traits;
use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;
trait Filterable
{
public function filter()
{
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return $users;
}
}
So now my function index() looks like this:
use Filterable;
public function index()
{
$this->authorize('view', Auth::user());
$users = $this->filter();
return UserResource::collection($users);
Now when i do this in my postman
{{url}}/api/users?filter[first_name]=anna
it works and it returns anna from my database but when I try
{{url}}/api/users?include=roles
it return every user from database but does not include roles.
Can somebody help me with this?
This is taken straight from the github page: https://github.com/spatie/laravel-query-builder#custom-filters
Custom filters
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
class FiltersUserPermission implements Filter
{
public function __invoke(Builder $query, $value, string $property) : Builder
{
return $query->whereHas('permissions', function (Builder $query) use ($value) {
$query->where('name', $value);
});
}
}
use Spatie\QueryBuilder\Filter;
// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
->get();
// $users will contain all users that have the `createPosts` permission
I've been trying to do this for a while now. Most of the time, I solve it by using accessors. I'm currently trying to get if the column exists and I created a function in my model which is suppose to return boolean.
Model code:
class Inventory extends Model
{
protected $attributes = ['inventory'];
protected $appends = ['colorThumb'];
public function hasAttribute($attr){
return array_key_exists($attr, $this->attributes);
}
}
Controller code:
public function allInvOperation(Request $request){
$inv = Inventory::where('is_deleted', 0)->with(['product', 'size','color'])->orderByDesc('id')->get();
if(!is_null($request->searchText)){
dd($inv->hasAttribute('inventory'));
$inv = Inventory::where('is_deleted', 0)->with(['product', 'size','color'])->orderByDesc('id');
if($request->inv_filter == 'inventory'){
$inv = $inv->where('inventory', 'like', "%".$request->searchText."%")->get();
}
if($request->inv_filter == 'code'){
$inv = $inv->whereHas('product', function ($q) use ($request){
$q->where('code', "%".$request->searchText."%");
})->get();
}
}
ERROR
Method Illuminate\Database\Eloquent\Collection::hasAttribute does not exist.
The code you are doing hasAttribute on is a Collection of objects, you need to use first on that query to get a single result on which you can later do hasAttribute
How to search by title in the ServiceType only? There is also a title field in the Package which should be avoided
For example, in the Model:
class Package extends Eloquent {
protected $table = 'package';
function serviceType()
{
return $this->belongsTo('ServiceType');
}
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->where('title', '=', $service);
}
}
Note:
There is a service_type_id field in the Package and id, title fields in the serviceType
in the controller:
$packages = Package::getPackagesByServiceType('something')->get();
No result appeared for some reason? It should search for something in the serviceType
It seem it wouldn't work to combine with() and where(). When I remove the where() and it work.
You can't use where() like that to filter by a related model. You should use whereHas() instead:
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->whereHas('serviceType', function($q) use ($service){
$q->where('title', '=', $service);
});
}
Note if you don't need serviceType in the packages afterwards you don't have to eager load it, ergo you can remove the with('serviceType')
Also if you call get() in the controller you should use a query scope. It offers the same functionality but it's not a static function and it's the Laravel way
public function scopeByServiceType($query, $service){
return $query->with('serviceType')->whereHas('serviceType', function($q) use ($service){
$q->where('title', '=', $service);
});
}
And you use it like this:
$packages = Package::byServiceType('something')->get();
class Package extends Eloquent {
protected $table = 'package';
function serviceType()
{
return $this->belongsTo('ServiceType');
}
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->where('title', '=', $service)->get();
}
}
You forgot the ->get();
The ->get() should be in the Model
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->where('title', '=', $service)->get(); // here
}
and in the controller it should be like this:
$packages = Package::getPackagesByServiceType('something');
Hope that helps... I had similar issues in my Model - Controller structure....
how can i use this in the model
now example 1 this work just fine... on the controller
$songs = DB::table('songlist')
->join('historylist', 'songlist.id', '=', 'historylist.songID')
->select('songlist.*', 'historylist.*')
->orderBy('historylist.date_played', 'DESC')
->first();
return View::make('currentsong')
->with('songs', $songs);
but i want to get that from the model my model is
class Radio extends Eloquent
{
public static $timestamps = true;
}
i want my model to look like
class Radio extends Eloquent
{
public static function getSonginfo()
{
$songs = DB::table('songlist')
->join('historylist', 'songlist.id', '=', 'historylist.songID')
->select('songlist.*', 'historylist.*')
->orderBy('historylist.date_played', 'DESC')
->first();
}
}
now how can i pass this model into my controller and view and call the varible as i do right now $songs->title on my view
the part i dont really get is how can i call the model function on the controller and parse it into the view something like this maybe
$songs = Radio::getSonginfo();
return View::make('currentsong')->with('songs', $songs);
now when i call this on my view {{ $songs->title}} i get undefined variable $songs.
any help Thanks.
sorry for my rusty english.
you need to return the variable in your model.
public static function getSonginfo()
{
$songs = DB::table('songlist')
->join('historylist', 'songlist.id', '=', 'historylist.songID')
->select('songlist.*', 'historylist.*')
->orderBy('historylist.date_played', 'DESC')
->first();
return $songs;
}