Appending Eloquent Attributes/Modified Relation Date on Query Building / Code Optimization - laravel

I'm looking for a solution to optimize my Code using Laravel Eloquent.
My issue is that I want to add Attributes conditionally, and this Attributes is basically the a transformed many-to-many relationship.
At the moment I have this in my controller (simplified):
<?php
namespace App\Http\Controller;
/**
* Class Category
*/
class Category extends Controller
{
/**
* #return Collection
*/
public function index()
{
return Category::withCount('countries')->get();
}
/**
* #param int $id
*
* #return Category
*/
public function show($id)
{
$result = Category::where('id', $id)
->with('countries')
->firstOrFail();
$result->countries_list = '';
return $result;
}
}
My Category model looks like this (simplified):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class Category
*/
class Category extends Model
{
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'countries',
];
/**
* #return string
*/
public function getCountriesCountAttribute()
{
return trans_choice('labels.countries', $this->original['countries_count']);
}
/**
* #return
*/
public function getCountriesListAttribute()
{
return $this->countries->pluck('alpha_2');
}
/**
* Get the related Countries.
*/
public function countries()
{
return $this->belongsToMany(
Country::class,
'category_country',
'category_id',
'country_id'
);
}
}
The Country Model is just a list of Countries with id, name, the Alpha2 Code, etc. I can't use the protected $appends to add countries_list because than the the list would be always included.
I also can't change my Countries model because this is used in several other occurrences.
What I'm looking for is a way to optimize the code in the controller to this:
<?php
namespace App\Http\Controller;
/**
* #return Collection
*/
public function index()
{
return Category::withCount('countries')->get();
}
/**
* #param int $id
*
* #return Category
*/
public function show($id)
{
return Category::where('id', $id)
->withAttribute('countries_list') // An array of all country aplha 2 codes
->firstOrFail();
}

You can access the countries_list attribute after querying (don't include it in your query).
public function show($id)
{
$category = Category::findOrFail($id);
$list = $category->countries_list; // this calls getCountriesListAttribute()
}

Related

Laravel Nova page detail not found due to The relationship

I am trying to test the tool I have been created. When I used relationship field in one of my resource, the page detail on this resource give me Not found.
/* My Relationship field */ (Ticket Resource)
HasMany::make(__('Replies'), 'replies',Reply::class)
/* Include */
use TicketWhmcs\TicketWhmcsPackage\Nova\Reply;
/* Ticket Model */
<?php
namespace TicketWhmcs\TicketWhmcsPackage\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use TicketWhmcs\TicketWhmcsPackage\Traits\API;
use TicketWhmcs\TicketWhmcsPackage\Models\TicketReplay;
class Ticket extends Model
{
use HasFactory, API;
protected $table = 'tickets';
protected $fillable = [
'tid',
'user_id',
'dept_id',
'subject',
'message',
'priority',
'status',
'admin',
];
public function department()
{
return $this->belongsTo(Department::class, 'dept_id', 'id');
}
/**
* Get all of the replies for the Ticket
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function replies()
{
return $this->hasMany(TicketReplay::class);
}
}
/* My resource */
namespace TicketWhmcs\TicketWhmcsPackage\Nova;
My Reply Resource
<?php
namespace TicketWhmcs\TicketWhmcsPackage\Nova;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
class Reply extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \TicketWhmcs\TicketWhmcsPackage\Models\TicketReplay::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/* Sort */
public static $sort = [
'id' => 'desc',
];
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id', 'admin',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make(__('ID'), 'id')->sortable(),
Text::make(__('Message'), 'message')->hideFromIndex(),
Text::make(__('Message'), 'message')->displayUsing(function ($value) {
return Str::limit($value, 50);
})->onlyOnIndex(),
Text::make(__('Author'), 'admin')->displayUsing(function ($value) {
if ($value) {
return 'Admin';
} else {
return 'You';
}
})->hideWhenCreating(),
Text::make('Last Update', 'updated_at')
->displayUsing(function ($lastActive) {
if ($lastActive === null) {
return null;
}
return $lastActive->diffForHumans();
})->hideWhenCreating(),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
public function authorizedToUpdate(Request $request)
{
return false;
}
public function authorizedToDelete(Request $request)
{
return false;
}
public static function indexQuery(NovaRequest $request, $query)
{
if (empty($request->get('orderBy'))) {
$query->getQuery()->orders = [];
return $query->orderBy(key(static::$sort), reset(static::$sort));
}
return $query;
}
}
I register My resource in NovaServiceProvider
public function resources()
{
Nova::resources([
Reply::class
]);
}
And it's worked!

How to get property or method in relationship ( laravel - eloquent )

in Post Model
function user()
{
return $this->belongsTo( \App\User::class);
}
in User Model
function posts()
{
return $this->hasMany( \App\Post::class);
}
function somedata()
{
return date('i') * 1000 + date('s');
}
in Controller
$posts = Post::query()
->where('id', 10)
->with('user')
->get();
but it does not get 'somedata' in user model .
How can I drag this data with posts ?
Try making it an attribute and append it in the model
Post.php
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = ['someData'];
/**
* Get the some data for the post.
*
* #return int
*/
public function getSomeDataAttribute()
{
return date('i') * 1000 + date('s');
}
You need to set an Accessor:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the user's somedata.
*
* #return string
*/
public function getSomedataAttribute()
{
return 'somedata';
}
}
Also see: https://laravel.com/docs/5.8/eloquent-mutators

Laravel - Query scopes across models

In a nutshell, I want to create a function that my query scopes can use across multiple models:
public function scopeNormaliseCurrency($query,$targetCurrency) {
return $query->normaliseCurrencyFields(
['cost_per_day','cost_per_week'],
$targetCurrency
);
}
I have got my logic working within this scope function no problem, but I want to make this code available to all my models, as there are multiple currency fields in different tables and I don't want to be replicating the code in each query scope - only specify the columns that need attention.
So, where would I make my function normaliseCurrencyFields? I have extended the Model class as well as used the newCollection keyword to extend Collection but both result in Call to undefined method Illuminate\Database\Query\Builder::normaliseCurrencyFields() errors.
I have looked into Global Scoping but this seems to be localised to a Model.
Am I along the right lines? Should I be targeting Eloquent specifically?
Create an abstract base model that extends eloquent then extend it with the classes you want to have access to it. I do this for searching functions, uuid creation, and class code functions. So that all of my saved models are required to have to certain attributes and access to my searching functions. For instance I created a static search function getobjectbyid(). So that when extended I can call it like so:
$user = User::getobjectbyid('habwiifnbrklsnbbd1938');
Thus way I know I am getting a user object back.
My base model:
<?php
/**
* Created by PhpStorm.
* User: amac
* Date: 6/5/17
* Time: 12:45 AM
*/
namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
abstract class Model extends Eloquent
{
protected $guarded = [
'class_code',
'id'
];
public $primaryKey = 'id';
public $incrementing = false;
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
$this->class_code = \App\Enums\EnumClassCode::getValueByKey(get_class($this));
$this->id = $this->class_code . uniqid();
return $this;
}
public static function getObjectById($id){
$class = get_called_class();
$results = $class::find($id);
return $results;
}
public static function getAllObjects(){
$class = get_called_class();
return $class::all();
}
my user model:
<?php
namespace App;
use Mockery\Exception;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use App\Model as Model;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'contact', 'username', 'email_address'
];
/**
* The column name of the "remember me" token.
*
* #var string
*/
protected $rememberTokenName = 'remember_token';
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token', 'active'
];
/**
* the attributes that should be guarded from Mass Assignment
*
* #var array
*/
protected $guarded = [
'created_at', 'updated_at', 'password_hash'
];
/**
* Define table to be used with this model. It defaults and assumes table names will have an s added to the end.
*for instance App\User table by default would be users
*/
protected $table = "user";
/**
* We have a non incrementing primary key
*
* #var bool
*/
public $incrementing = false;
/**
* relationships
*/
public function contact(){
// return $this->hasOne(Contact::class, 'id', 'contact_id');
return $this->hasOne(Contact::class);
}
public function customers(){
// return $this->hasOne(Contact::class, 'id', 'contact_id');
return $this->hasMany(Customer::class);
}
/**
* User constructor.
* #param array $attributes
*/
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
// Your construct code.
$this->active = 1;
return $this;
}
/**
* #param $password string
* set user password_hash
* #return $this
*/
public function setPassword($password){
// TODO Password Validation
try{
$this->isActive();
$this->password_hash = Hash::make($password);
$this->save();
} catch(\Exception $e) {
dump($e->getMessage());
}
return $this;
}
/**
* Returns whether or not this use is active.
*
* #return bool
*/
public function isActive(){
if($this->active) {
return true;
} else {
Throw new Exception('This user is not active. Therefore you cannot change the password', 409);
}
}
public function getEmailUsername(){
$contact = Contact::getObjectById($this->contact_id);
$email = Email::getObjectById($contact->email_id);
return $email->username_prefix;
}
/**
* #return string
*
* getFullName
* returns concatenated first and last name of user.
*/
public function getFullName(){
return $this->first_name . ' ' . $this->last_name;
}
/**
* Get the name of the unique identifier for the user.
*
* #return string
*/
public function getAuthIdentifierName(){
return $this->getKeyName();
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier(){
return $this->{$this->getAuthIdentifierName()};
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword(){
return $this->password_hash;
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken(){
if (! empty($this->getRememberTokenName())) {
return $this->{$this->getRememberTokenName()};
}
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value){
if (! empty($this->getRememberTokenName())) {
$this->{$this->getRememberTokenName()} = $value;
}
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName(){
return $this->rememberTokenName;
}
/**
* Get the e-mail address where password reset links are sent.
*
* #return string
*/
public function getEmailForPasswordReset(){
}
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token){
}
public function validateAddress(){
}
}
a TestController:
public function test(){
$user = User::getObjectById('USR594079ca59746');
$customers = array();
foreach ($user->customers as $customer){
$contact = Contact::getObjectById($customer->contact_id);
$name = PersonName::getObjectById($contact->personname_id);
$c = new \stdClass();
$c->id = $customer->id;
$c->name = $name->preferred_name;
$customers[] = $c;
}
$response = response()->json($customers);
return $response;
}
Take note on how getObjectById is extended and available to my other classes that extend my base model. Also I do not have to specify in my user model an 'id' or 'class_code' and when my user model is constructed it calls the parent constructor which is the constructor on my base model that handles 'id' and 'class_code'.

I can't get data when i am editing in laravel 5.1

i have address Book table and user table i am assigning
the many user in my address book while i am created everything is fine(ok)
but when i am editing every data back in my form without assign user .
how can i get the user in editing form ?? this is my Address Book Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\AddressRequest;
use App\Http\Requests;
use App\Models\Address;
use App\Models\User;
use App\Http\Controllers\Controller;`enter code here`
use Illuminate\Pagination\Paginator;
use Auth;
use DB;
use Session;
class AddressesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Request $request)
{
Session::forget('searchaddress');
$addresses = Address::orderby('company_name');
$company_name = $request->input('company_name');
if(!empty($company_name)) {
//$addresses->where('company_name','LIKE','%'.$company_name.'%');
$addresses->where('company_name','LIKE','%'.$company_name.'%');
Session::set('searchaddress', $company_name);
}
$addresses = $addresses->paginate(5);
return view('address.index',compact('addresses'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$users = User::lists('first_name','id');
return view('address.create',compact('users'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(AddressRequest $request)
{
$address = Address::create($request->all());
$firstname = Auth::user()->first_name;
$lastname = Auth::user()->last_name;
$address->created_by =$firstname." ".$lastname;
$address->users()->attach($request->input('user_list'));
$address->save();
return redirect('/addresses');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$address = Address::find($id);
return view('address.show',compact('address'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
return view('address.edit',compact('address','users'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update( AddressRequest $request ,$id)
{
$address = Address::findOrFail($id);
$address->update($request->all());
$address->users()->sync($request->input('user_list'));
return redirect('/addresses');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$address = Address::find($id);
$address->delete();
return redirect('/addresses');
}
}
and that is my AddressBook Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
protected $fillable = [
'created_by',
'company_name',
'phone',
'email', 'address','comment'
];
public function users()
{
return $this->belongsToMany('App\Models\User')->withTimestamps();
}
public function getUserListAttribute()
{
return $this->users->lists('id');
}
}
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/D4jXQ.png
You have belongsToMany relation, so in your edit action you also should get current Address users like this
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
$address_users = $address->users->lists('id')->toArray();
return view('address.edit',compact('address','users', 'address_users'));
}
then in your view in select you should intersect arrays of $users and $address_users to get selected options.
{!! Form::select('user_list[], $users, isset($address_users) ? $address_users : null, ['id' => 'users_list', 'class' => 'form-control', 'multiple']) !!}
to avoid
isset($address_users) ? $address_users : null
you can define empty address_users array in your create method and do it like this
$address_users

Laravel 5 Querying Relationship

Here is the relationship 1 code:
/**
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function address()
{
return $this->hasMany('App\IPAddress', 'group_id');
}
and relationship 2 code:
/**
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function group()
{
return $this->belongsTo('App\IPGroups');
}
I want to get all ip addresses that belongs to specified group. I don't want to write raw queries, I need to be done with querying relationship. Does anyone has an idea?
I tried to do something like this:
/**
* Get IP Addresses of specified group
* #param Request $request
* #return mixed
*/
public function getIP(Request $request)
{
$group = IPGroups::findOrFail($request->group_id);
return $group->address;
}
but I need to add one where statement where I can pick only active ip addresses.
Here is the model 1 code:
namespace App;
use Illuminate\Database\Eloquent\Model;
class IPGroups extends Model
{
/**
* Working Table
* #var string
*/
protected $table = 'ip_groups';
/**
* Guarded Values From Mass Assignment
* #var array
*/
protected $guarded = [ 'id' ];
/**
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function address()
{
return $this->hasMany('App\IPAddress', 'group_id');
}
}
and the second model code:
namespace App;
use Illuminate\Database\Eloquent\Model;
class IPAddress extends Model
{
/**
* Working Table
* #var string
*/
protected $table = 'ips';
/**
* Protected Values From Mass Assignment
* #var array
*/
protected $fillable = [ 'group_id', 'ip', 'description', 'status' ];
/**
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function group()
{
return $this->belongsTo('App\IPGroups');
}
}
Try this, getting only the addresses with status as 'Active':
return $group->address->where('status','Active');
The reason this doesn't work:
return $group->address->where('status','=','Active');
is that the where we are using here is the where of the class Collection, which doesn't accept a comparator as second parameter as the where of the Models do.

Resources