Query scope in different table using Laravel 4 - laravel-4

I am using scope query in my Group list display, and Group belongs to Country table. I can use group name as search and sort order without any problem.
Want I want to do now are the following:
1) search country name which is stored in Country table
2) sort order country name which is stored in Country table
# Group Model #
class Group extends Eloquent
{
protected $table = 'group';
protected $guarded = array('id');
public function country()
{
return $this->belongsTo('country');
}
public function scopeName($query, $name)
{
return $query->where('group_name', 'LIKE', "%$name%");
}
public function scopeSortName($query, $order_by = 'asc')
{
return $query->orderBy('group_name', $order_by);
}
}
# Country Model #
class Country extends Eloquent
{
protected $table = 'country';
public function groups() {
return $this->hasMany('group');
}
}
# Group Controller #
public function index()
{
// search group name
$groups = Group::name($s_name);
// order group name
$groups = $groups->sortName($orderBy);
}

I don't think there is a way that I can sort the record using other column's table without joining it. Therefore in my controller I used JOIN query.
# Group Controller #
public function index()
{
// join the table Group and Country tables
$groups = Group::join('country', 'country.id', '=', 'group.country_id');
// search group name
$groups = $groups->name($s_name);
// order group name
$groups = $groups->sortName($orderBy);
}

Related

Laravel How To Update Nested createMany

Been having a hard time on figuring out how to implement updating records on a nested createMany based on the store method. I have these models and relations:
User Model:
class User extends Model
{
public function orders() {
return $this->hasMany(Order::class);
}
}
Order Model:
class Order extends Model
{
public function user() {
return $this->belongsTo(User::class);
}
public function subOrders() {
return $this->hasMany(SubOrder::class);
}
}
SubOrder Model:
class SubOrder extends Model
{
public function order() {
return $this->belongsTo(Order::class);
}
public function subOrderProducts() {
return $this->hasMany(SubOrderProducts::class);
}
}
SubOrderProducts Model:
class SubOrderProducts extends Model
{
public function subOrder() {
return $this->belongsTo(SubOrder::class);
}
}
Here are the tables:
orders table:
id name
sub_orders table:
id order_id date price
sub_order_products table:
id sub_orders_id product_id
Then on the store method:
public function store(StoreOrderRequest $request) {
$order = auth()->user()->orders()->create($request->validated());
$order_subs = $order->subOrders()->createMany($request->orders);
$order_sub_products = $request->only('subproducts');
foreach ($order_subs as $key => $value) {
$order_sub->subOrderProducts()->createMany($order_sub_products[$key]['products']);
}
}
What I wanted to achieve is to update or create those sub orders and sub order products. If the sub order is already existing, then update, otherwise create a new record with those corresponding sub order products.
Here's what I've tried so far:
public function store(UpdateOrderRequest $request, Order $order) {
$order->update($request->validated());
$order_subs = $order->subOrders()->updateMany($request->orders);
$order_sub_products = $request->only('subproducts');
foreach ($order_subs as $key => $value) {
$order_sub->subOrderProducts()->updateMany($order_sub_products[$key]['products']);
}
}
It's not working as expected since the order subs is only a single record. What's the best way or the right process for updating/creating these records? Thanks.

Laravel query builder with the User and Auth

How to List all rows from a table (agendas) in my DB where records are saved by the connected user.I'm using default Auth from Laravel.
public function index ($id = null)
{
$agendas = Agenda::where('id', Auth::user()->id)->get();
$users = User::all();
return view('admin.agendas.index', compact('agendas','users','id'));
}
My controller here.
Need help
Assuming
agendas table (containing records for Agenda model) has a column user_id which references the id column on users table
User hasMany Agenda
Agenda belongTo User
class User extends Model
{
public function agendas()
{
return $this->hasMany(Agenda::class);
}
//... rest of class code
}
class Agenda extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
//... rest of class code
}
public function index($id = null)
{
$user = User::with('agendas')->findOrFail(auth()->id());
return view('admin.agendas.index', [
'user' => $user,
'agendas' => $user->agendas,
'id' => $id
]);
}
Your User model should have a relationship:
public function agendas()
{
return $this->hasMany(Agenda::class);
}
In your controller, you could then simplify the use as such:
public function index (Request $request, $id = null)
{
$agendas = $request->user()->agendas;
$users = User::all();
return view('admin.agendas.index', compact('agendas','users','id'));
}
if you wanna get data related to another data , you have to join those tables together by a field. in this case i guess you have a column in Agenda table named 'user_id'.
you have two way :
join tables in your Model.
search in Agenda table in your controller
if you want to use joining your tables from model :
// in App\User.php
...
class User ...{
...
public function Agenda(){
return $this->hasMany(Agenda::class);
}
...
}
...
then you can access to all of "Agenda" from everywhere like this :
Auth()->user()->agenda
if you want to search in table from your controller you can do :
Agenda::where('id', Auth::user()->id)
you can read more about eloquent-relationships in : https://laravel.com/docs/8.x/eloquent-relationships

Retrieving relevant record from a relationship

I am allowing user to search by type which is passed into a function:
public function typeSearch($type)
{
$events = Event::where('type', $type)
->with('entities')
->get();
return view('events.searchResultEvents', compact('events'));
}
Which works nearly as it's supposed to do, it does retrieve the entities but not the right entities for example:
Event id = 25, entity_id = 2 it retrieves: Entities id = 25 while it should be 2.
How can I change this so it retrieves the right record?
Example::
Looking at the image, Event is = 25 and entity_id = 1. entity_id is a foreign key which is linked to id on 'entities' table
From Relations we have 'entities' with id = 25, while it should be 1 as entity_id = 1
Event model::
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Event extends Model
{
protected $table = 'events';
public $timestamps = true;
use Searchable;
public function entities()
{
return $this->belongsTo('App\Entity', 'id');
}
public function users()
{
return $this->belongsTo('App\User', 'id');
}
public function events()
{
return $this->belongsTo('App\DirtyEvent', 'id');
}
}
I think there's problem in your relations method.
public function entities()
{
return $this->belongsTo('App\Entity', 'id'); // Ithink you need to change it
}
Change that 'id' in your second parameter to 'entity_id'
public function entities()
{
return $this->belongsTo('App\Entity', 'entity_id');
}
The second parameter is used like this, I don't know how to explain it in technical but here's an example:
$event = Event::find(1);
//this will return the events with id=1 and that data have entity_id=2
$entities = $event->entities;
//If you set the second parameter in your Event model to 'id',
//this $entities variable contain the data from entities table with id=1, because your $event id=1
//But if you set the second parameter to 'entity_id'
//this $entities variable contain the data from entities with the id=2, because your $event entity_id=2

Laravel Eloquent hasMany and BelongsToMany not returning using with

I am trying to do a single query to get back an order and the card to charge, but getting an error.
Card model:
class Card extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function orders()
{
return $this->hasMany('Order');
}
}
Order model:
class Order extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function card()
{
return $this->hasOne('Card');
}
public function address()
{
return $this->belongsTo('Address');
}
public function orderItems()
{
return $this->hasMany('OrderItem');
}
}
What I am trying to get back:
$order = Order::with('card')->find($id);
This obviously doesn't work and I have tried several combos. I think the issue is with my models/relationships.
Any idea how I can get back the order with the card/token details?
DB info: Each order can have only one card_id and each card can be in many orders. There is no order_id in the card.
Orders table basically:
id | card_id
Cards table:
id | token
Trying to get the token col to return with the Order.
In your Order model, you need to change this:
public function card()
{
return $this->hasOne('Card');
}
to this:
public function card()
{
return $this->belongsTo('Card');
}
The reason is that you are defining the inverse of the hasMany relationship. With the belongsTo relationship, Eloquent will look for a card_id column on the orders table.

Self join in Laravel

I am trying to build a self join in Laravel. I wish to compare 2 columns in the same table.
When I write this in my controller:
$char_name_obj = User::find($user->id)->characters()->where('lord_id', '=', 'id')->get();
lord_id is one column, id is the other column in the same table named characters. This returns nothing. I am sure I need to do a self join to be able to achieve this.
Character model:
class Character extends Eloquent {
protected $table = 'characters';
protected $fillable = array('lord_id','char_name', 'char_dynasty', 'picture');
public function user()
{
return $this->belongsTo('User');
}
public function Titles()
{
return $this->hasMany('Title');
}
public function LordCharID()
{
return $this->has_one('Character');
}
}
I don't know how to use the last function LordCharID().
has_one is the Laravel 3 function; so if you're using Laravel 4, you need to use hasOne
You can use whereRaw to compare columns:
User::find($user->id)->characters()->whereRaw('lord_id = id')->get();

Resources