Laravel hasOne relationship on Laravel's batch ID - php

I need to be able to join an entry from Laravel's job_batches table onto one of my own tables & model which contains reference to a batch ID.
I'd like to do this through the model using the hasOne relationship but when I try to do this I'm getting an error:
Class 'App\Models\Illuminate\Support\Facades\Bus\Batch' not found
What am I missing here?
My model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
class CSVUploadSchedule extends Model
{
use SoftDeletes;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'csv_upload_schedules';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'csv_name',
'csv_path'
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'processed_at' => 'datetime',
'start_processing_at' => 'datetime'
];
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = [
'batch'
];
/**
* Get the batch associated with the schedule.
*/
public function batch()
{
return $this->hasOne(Illuminate\Support\Facades\Bus\Batch::class, 'id','batch_id');
}
}

Related

Why Are Methods Not Found In Authenticatable? Using Laravel 6 Cashier 10 With Stripe API?

Why are methods not found in Authenticatable? Im using Laravel 6 Cashier 10 with Stripe API. Please see the following errors in my Subscription Controller.
Method 'createSetupIntent' not found in \Illuminate\Contracts\Auth\Authenticatable|null
Method 'addPaymentMethod' not found in \Illuminate\Contracts\Auth\Authenticatable|null
Unhandled \Stripe\Exception\ApiErrorException
The above errors show in up in PHP storm. When the code is actually ran in the browser, I get this error: ... This makes sense considering PHP Storm cant find my methods. What do you guys think?
This customer has no attached payment source or default payment method.
Here is my User model.
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use Laravel\Cashier\Billable;
use Illuminate\Foundation\Auth;
class User extends Authenticatable
{
use Billable, Notifiable;
protected $connection = 'mongodb';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', 'password', 'phone',
];
/**
* The collection name
*
* #var array
*/
protected $collection = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

Laravel Unit test fails with custom attributes

I'm trying to write a unit test on my user model that tests if the soft deleted record is still present in the database.
/**
* check if users are soft deleted only
*
* #return void
*/
public function testUserIsSoftDeleted()
{
$user = factory(User::class)->create();
$user->delete();
$this->assertSoftDeleted('users', $user->toArray());
}
This test runs fine until I add a custom attribute to the model.
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use OwenIt\Auditing\Contracts\Auditable;
class User extends Authenticatable implements MustVerifyEmail, Auditable
{
use HasApiTokens, Notifiable, SoftDeletes, HasRoles, \OwenIt\Auditing\Auditable;
protected $guard_name = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password', 'active', 'activation_token', 'email_verified_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'activation_token'
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The attributes that should be added to the JSON response
*
* #var array
*/
protected $appends = ['md5_email'];
/**
* Convert email address into md5 string
*
* #var string
*/
public function getMd5EmailAttribute()
{
return md5(strtolower(trim($this->email)));
}
}
When I run the test I get the following error.
How do I include custom attributes in the Found array?
To skip md5_email from the query, assign the toArray result to an array and unset the md5_email
Something like
public function testUserIsSoftDeleted()
{
$user = factory(User::class)->create();
$user->delete();
$userInfoArray = $user->toArray()
// This should skip md5_email getting added to the query
unset($userInfoArray["md5_email"])
$this->assertSoftDeleted('users', $userInfoArray);
}
As stated by Cerlin the md5_email attribute in not present in the database, that's why you get the error. You have many options to make the test pass. You might simply unset the md5_email from the user array or, for the sake of clarity, rewrite your test as follow:
/**
* check if users are soft deleted only
*
* #return void
*/
public function testUserIsSoftDeleted()
{
$user = factory(User::class)->create();
$user->delete();
$this->assertSoftDeleted('users', $user->only('id', 'name', 'email'));
}

How to query in terms of two columns in laravel eloquent orm

I need help to make a query in laravel.
I have three tables
1)Category(Contains id and name column).
2)Geometry(Contains id and name column).
3)practical(Contains id and name column and the Category_id,Geometry_id column/keys )
Now i want to search the practicals in terms of Category_id and Geometry_id.
The Practical.php model file is..
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Model;
use App\Models\Practical;
class Practical extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table='practical';
protected $fillable = [
'name',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
public function category()
{
return $this->belongsTo('App\Models\Category');
}
public function geometry()
{
return $this->belongsTo('App\Models\Geometry');
}
}
The Category and Geometry Model code is
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Model;
use App\Models\Geometry;
class Geometry extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table='geometry';
protected $fillable = [
'name',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
public function practical()
{
return $this->hasMany('App\Models\Practical');
}
}
I know how to query using only one ID.Category or geometry like this..
$Categories=Category::where('id',1)->firstOrFail();
but i failed to query by checking both the ids of Category and Geometry.
Now i want to search the practicals in terms of Category_id and Geometry_id
If you want to search practicals by category ID and geometry ID, just do a simple query:
Practical::where('category_id', $categoryId)
->where('geometry_id', $geometryId)
->get();

Eloquent Laravel foreign key to spivot table

I want to make a foreign key relation to a spivot table in Laravel.
Thats what the schema looks like:
I need to make a relation from the 'roles' table to the spivot table 'organisations_users'.
I want to do this with the column 'role_id' in the 'organisations_users' table.
Now my question is: How do I make this relationship in my models in Laravel. I'm using Laravel Eloquent.
I've already made 2 models 'User' and 'Organisation'.
This is the code:
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = [];
public function organisations(){
return $this->belongsToMany('App\Models\Organisation', 'organisations_users')->withPivot('date_start','date_stop','role_id');
}
}
This is the 'User' model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Organisation extends Model
{
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = [];
public function users(){
return $this->belongsToMany('App\Models\User', 'organisations_users')->withPivot('date_start','date_stop','role_id');
}
}
This is the 'Organisation' model.

Laravel 5 get row from relationship model

I have the following relationship models setup:
User
Users can have many job titles
Users can have many employee types
<?php
namespace App\Models\User;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['first_name', 'last_name', 'email', 'status', 'activation_code'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token', 'activation_code'];
/**
* The roles that belong to the user.
*
* #return Object
*/
public function roles()
{
return $this->belongsToMany('App\Models\User\Role')->withTimestamps();
}
/**
* The employee types that belong to the user.
*
* #return Object
*/
public function employeeTypes()
{
return $this->belongsToMany('App\Models\User\EmployeeType')->withTimestamps();
}
/**
* The job itles that belong to the user.
*
* #return Object
*/
public function jobTitles()
{
return $this->belongsToMany('App\Models\User\JobTitle')->withTimestamps();
}
}
Now, I want to be able to select the a list of users and all their job titles and employee types.
I have tried something like this with no such luck! Please could someone advise how this is possible?
$this->user->whereIn('id', $ids)->jobTitles()->get();
The above code gives the error:
Call to undefined method Illuminate\Database\Query\Builder::jobTitles()
Use eager loading:
$this->user->whereIn('id', $ids)->with('jobTitles', 'employeeTypes')->get();
You can only call relationships directly from a model, that's why your attempt failed (whereIn() returns Builder).
Eager/nested loading is very efficient way to fetch data before looping through multiple models and their relations (otherwise you may end up having A LOT of db queries) ;)

Categories