WhereBetween not found on eloquent hasmany - laravel

Using Laravel 5. I have a model Property, that has many Weeks available to it. This is the Property Model.
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* #property mixed week
*/
class Property extends Model
{
public function week()
{
return $this->hasMany('App\Models\Week', 'PropertyID', 'PropertyID');
}
}
I am trying to use WhereBetween on a hasMany relation of an object using the WhereBetween method. This is the error I get though.
Method 'WhereBetween' not found in class 'illumainate\Database\Eloquent\Relations\HasMany.
list($from, $to) = $params->get('range');
$week = $property->week()
->whereBetween('WeekDate', array($from, $to))
->get();
The same error occurs if I try WhereRaw instead of WhereBetween. hasMany class doesn't have WhereRaw or WhereBetween. Is there a way around this?

I had a similar issue in Laravel 5.2 with the following code:
$events = Events::whereBetween('start', array($start, $end))
->whereBetween('end', array($start, $end))
->get();
This throws an error like:
Call to undefined method App\Events::whereBetween()
Somehow in Laravel 5.0+ I could not use whereBeetween directly on the model. But in the API documentation whereBetween is still listed as function of the DB class (see here). By replacing the model with the DB class we can fix it:
use DB;
...
$events = DB::table('events')
->whereBetween('start', array($start, $end))
->whereBetween('end', array($start, $end))
->get();

Related

How to retrieve record from Eloquent Model?

This sounds stupid but I can't find a way to retrieve a record from eloquent model Gallery.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Gallery extends Model
{
use HasFactory;
protected $fillable = ['text'];
}
Calling from a Route in web.php:
$data = Gallery::with('id', '=', 1)->get();
throws this error in laravel.log:
local.ERROR: Call to undefined relationship [id] on model [App\Models\Gallery]. {"exception":"[object] (Illuminate\\Database\\Eloquent\\RelationNotFoundException(code: 0): Call to undefined relationship [id] on model [App\\Models\\Gallery]. at /Users/artur/PhpstormProjects/strong-moebel.art/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:35)
The only thing that works is:
$data = Gallery::all();
The with() method at:
Gallery::with
Is used to refer to relationship with another model.
If you are looking to get data from just the Gallery model change with() to where() as below:
$data = Gallery::where('id', '=', 1)->get();
This will return a collection (think of it as an object containing an array of the results).
If you're trying to access additional data from a related model you will need to setup the relationships as per the Laravel documentation.
If you want just the instance of Gallery related to that id, you can get it with
$gallery = Gallery::where('id', '=', 1)->first();
// or
$gallery = Gallery::find(1);

Property does not exist in collection while using belongsToMany in laravel eloquent

I am using Laravel 8.X and eloquent to develop a web app.
I have a pivot table 'portal_event_users'
I am trying to add a belongsToMany relationship to the portal_users in the model of portal_event_users table.
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class EventUser extends Model
{
use HasFactory;
protected $table = 'portal_event_users';
public function users()
{
return $this->belongsToMany(User::class);
}
public function events()
{
return $this->belongsToMany(Event::class);
}
}
I have the following statements in the controller
$eventusersobj = \App\Models\EventUser::select('*')
->where('event_id', '=', $event_id)
->get();
$response = $eventusersobj->users->keyBy('id');
It is returning the following error
Property [users] does not exist on this collection instance.
Can someone please advice on how can i change this error?
Thanks in advance
As it returns a collection, you can use pluck()
$eventusersobj->pluck('users')->each(function($user){
$user->keyBy('id');
})

Is it possible to work in a model with query builder using Laravel?

I would like to know if is it possible to work in a model using query builder to make a join between two tables, I don't want to use eloquent
this is my model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class Tbl_Perimetro extends Model
{
puplic function perimetros(){
$carteras = DB::table('tbl_perimetros')
->join('tbl_equipo_postventaatcs', 'tbl_equipo_postventaatcs.id', '=', 'tbl_perimetros.postventaatc_id')
->join('tbl_lista_carteras', 'tbl_equipo_postventaatcs.carteras_id', '=', 'tbl_lista_carteras.id')
->get();
return $carteras;
}
}
If you just want to use query builder you could to do so. But I realy recomend to use eloquent methods.
Also, is important to look about mutators, appends and scopes options to models that could help you more than query builder alone.
Other appointments:
DB::table('tbl_perimetros') could be replaced by $this in this model
Do not forget return for the method.
Try protect $appends = ['perimetros'] and rename method to getPermietrosAttribute to return perimetros as an item in model object.

Laravel 5.5 issue in fetching data through eloquent model

The database table is : prefix_adminUsers and I have a model in UserAdmin.php as below:
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class UserAdmin extends Model
{
protected $table = 'adminUsers';
public $timestamps = false;
}
When I tried to access the same by controller it show me the error:
Illuminate\Database\Eloquent\Builder Object ( [query:protected] =>
Illuminate\Database\Query\Builder Object ( [connection] =>
Illuminate\Database\MySqlConnection Object ( [pdo:protected] => PDO
Object
my controller is as follows:
use App\Model\UserAdmin;
$userRecord = UserAdmin::where('id', '=', Auth::user()->id);
print_r($userRecord);
It's not an error, you are printing the eloquent class Builder, used to build the queries to retrieve the model data, but it doesn't give you the results yet because you are missing ->get() at the end.
Your code should look like:
use App\Model\UserAdmin;
$userRecord = UserAdmin::where('id', '=', Auth::user()->id)->get();
print_r($userRecord);
You can read more how to retrieve Models on the Laravel 5.5 docs.
Since each Eloquent model serves as a query builder, you may
also add constraints to queries, and then use the get method to
retrieve the results.

Laravel eloquent get all from one table and one from another

I'm fetching with $articles = Article::all(); for an index-page (using foreach with $articles as $article) all of my articles in a table. Now I want to join this results with another table called 'devices' and only want add one column named 'name' to my result in $articles.
The 'id' of the devices if equal to the 'device_id' in my articles-table.
I can make a big select with
$articles = DB::table('articles')
->join('devices', 'articles.device_id', '=', 'devices.id')
->select('devices.name','articles.id','articles.text', ...)
->get();
but I don't want to do this. Is there any better option to handle this?
Thank you in advance,
quantatheist
You can use relationship in Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Article extends Eloquent{
public function device(){
$this->belongsTo('App\Models\Device');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Device extends Eloquent{
public function articles(){
$this->hasMany('App\Models\Article');
}
}
And after when you get $articles = Article::all();
You can loop through articles
foreach($articles as $article){
echo $article->device->name
}
Also you can eager or lazy load relationship $articles = Article::with('device')->all();
And more you can take all artciles for particular device
Device::find(1)->articles()->get()

Resources