Get if following page - laravel

I'm trying to get if user following or no the page. I'm try like this:
class Page extends Model
{
public function get_following()
{
return $this->belongsTo(Followers::class, 'user_id')->where('type', '=', 1)->where('follower_id', auth()->user()->id)->Select('id');
}
}
But this return null.
dd($page)
Page {#303 ▼
#attributes: array:9 [▼
"id" => 1
]
#relations: array:3 [▼
"ptag" => Tag {#307 ▶}
"get_following" => null
Table followers:
followers.user_id = (pages.id), follower_id = (auth user), type = (1)
Thank you.

change select to ->value('id')
public function get_following()
{
return $this->belongsTo(Followers::class, 'user_id')->where('type', '=', 1)->where('follower_id', auth()->user()->id)->value('id');
}

Try:
public function get_following()
{
return $this->belongsTo(Followers::class, 'user_id')
->where('type', '=', 1)
->where('follower_id', auth()->id())
->pluck('id');
}

public function get_following()
{
return $this->belongsTo('\App\Followers', 'user_id')
->where('type', 1)
->where('follower_id', Auth::user()->id())
->pluck('id');
}

Related

how can we use with method in laravel with where clause?

i need only those products where variants size field is tiny. what i should do ? above quering giving me all products but with empty variants
$result=$categories->with([
'products' => function ($product) {
return $product->with([
'variants' => function ($variants) {
return $variants->where('size','tiny');
}
]);
}
])->get();
Change your code like this.
$result=$categories->with([
'products' => function ($product) {
return $product->whereHas(
'variants', function ($variants) {
return $variants->where('size','tiny');
}
]);
}
])->get();

Laravel Using nested with

I couldn't do what I wanted to do with Laravel, actually what I want to do is as follows,
I send getTruck id and list truckHistory with witdh, and I want to pull trukInvoice information with truckHistory invoice_id. But i am getting error where am i doing wrong?
Mysql Connection is as follows.
http://localhost:3000/truck/1
"trucks" table column "plate"
"invoice_details" column "plate_no"
"invoice_details" column "invoice_id"
"invoice" column "id"
Truck Controller
public function getTruck($id)
{
$truck = Truck::find($id)->with([
'truckHistory' => function($query){
// return $query->with(['trukInvoice']);
}
])->first();
return $truck;
}
Truck Model
public function companys()
{
return $this->belongsTo(Contact::class, 'company_id', 'id');
}
public function getCompanyNameAttribute()
{
return $this->companys()->first()->name;
}
public function truckHistory(){
return $this->hasMany(InvoiceDetail::class,'plate_no','plate');
}
public function trukInvoice(){
return $this->belongsTo(Invoice::class,'invoice_id','id');
}
Try this:
$truck = Truck::leftJoin('invoices', 'trucks.invoice_id', 'invoices.id')
->leftJoin('invoice_details', 'trucks.plate_no', 'invoice_details.plate')
->select('*')
->first();
or
$truck = Truck::with(['invoices' => function ($query) {
$query->whereHas('invoice_details', function ($q){
$q->whereNotNull('invoice_details.plate');
});
}])->first();
Check the documentation on restraining eager loads.

My array has only one item from pivot table

With this code :
$evenements = Year::with(['evenements' => function($query) {
return $query->orderBy('mnemonique');
}])
->orderBy('id')
->get();
I get that:
5 => array:7 [▼
"id" => 62
"name" => "Congé"
"mnemonique" => "Congé"
"color" => "#bcbcbc"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"pivot" => array:2 [▼
"year_id" => 1
"evenement_id" => 62
The problem is that pivot should have 10 items and not only 2 because the event 62 is in 5 years
This is the models code:
Events model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Evenement extends Model
{
protected $fillable = ['name','mnemonique','color'];
//DD 18/07/21 Une année peut avoir plusieurs events
public function years()
{
return $this->belongsToMany(Year::class, 'evenement_year', 'evenement_id', 'year_id');
}
}
Year model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Year extends Model
{
protected $fillable = ['name'];
public function evenements()
{
return $this->belongsToMany(Evenement::class, 'evenement_year', 'year_id', 'evenement_id');
}
}
This is the content of $query :
Illuminate\Database\Eloquent\Relations\BelongsToMany {#260 ▼
#table: "evenement_year"
#foreignPivotKey: "year_id"
#relatedPivotKey: "evenement_id"
#parentKey: "id"
#relatedKey: "id"
#relationName: "evenements"
#pivotColumns: []
#pivotWheres: []
#pivotWhereIns: []
#pivotWhereNulls: []
#pivotValues: []
+withTimestamps: false
#pivotCreatedAt: null
#pivotUpdatedAt: null
#using: null
#accessor: "pivot"
#query: Illuminate\Database\Eloquent\Builder {#1478 ▶}
#parent: App\Year {#1474 ▶}
#related: App\Evenement {#1475 ▶}
}
I don't know how to feed pivot array ? Do you have any idea ?
Thank you in advance.
You must specify extra columns in your relationship using withPivot; since I do not know your column names (cropped in image), I will just give an example:
class Year extends Model
{
protected $fillable = ['name'];
public function evenements()
{
return $this->belongsToMany(Evenement::class, 'evenement_year', 'year_id', 'evenement_id')
->withPivot(["someField1", "someFiled2"]);
}
}

Where clause in polymorphic relationship

I have the tables
threads
- id
replies
- id
- repliable_id
- repliable_type
I want to add another column to the Thread, which is the id of the most recent reply.
Thread::where('id',1)->withRecentReply()->get()
And the following query scope
public function scopeWithRecentReply() {
return $query->addSelect([
'recent_reply_id' => Reply::select('id')
->whereHasMorph('repliable', ['App\Thread'], function ($q) {
$q->where('repliable_id', '=', 'threads.id');
})->latest('created_at')
->take(1),
]);
}
I have also tried
public function scopeWithRecentReply() {
return $query->addSelect([
'recent_reply_id' => Reply::select('id')
->where('repliable_id', '=', 'threads.id')
->latest('created_at')
->take(1),
]);
}
But in both cases the
recent_reply_id => null
If instead of threads.id i enter an integer, it works and the recent_reply_id is not null
For example
public function scopeWithRecentReply() {
return $query->addSelect([
'recent_reply_id' => Reply::select('id')
->whereHasMorph('repliable', ['App\Thread'], function ($q) {
$q->where('repliable_id', '=', 1);
})->latest('created_at')
->take(1),
]);
}
My question is
Is there a way to be able to fetch the recent_reply_id using the respective threads.id ?
I would suggest using appends instead of query scopes so in your Thread model we will add
protected $appends = ['recent_reply_id'];
.....
public function replies () {
// you need to add here your relation with replies table
}
public function getRecentReplyIdAttribute () {
return $this->replies()->latest('id')->first()->id;
}
now wherever you query the threads table you will have access to recent_reply_id like
$thread = Thread::where('id',1)->withRecentReply()->get();
$thread->recent_reply_id;

laravel collection nested query

I'm new with laravel collection . i just want to make this query with collection
DB::select(SELECT id, user_id, created_at,latitude,longitude
FROM coordinates
WHERE created_at IN (
SELECT MAX(created_at)
FROM coordinates
GROUP BY user_id));
according to the document https://laravel.com/docs/6.x/collections
this what i did and it gives me all the data
$this->data['information'] = collect($response->json()['items']);
Edit:
simply i need to produce that query (that i mentioned above) by using Collection.
This is the contents of $response->json()['items']
"#items: array:17 [▼ 0 => array:9 [▼ "id" => 977777779 "platform_id" => "msaeed" "platform_type" => 1 "status" => 1 "longitude" => 1.1 "latitude" => 1.1 "created_by" => "NMF" "created_at" => "2019-10-27T21:00:00Z" "updated_at" => "2019-10-28T07:58:36Z""
any help would be appreciated
Here is the query.
$data = collect($response->json()['items']);
$data = $data->whereIn('created_at', $data->sortByDesc('created_at')
->groupBy('user_id')
->pluck('0.created_at'))
->onlyKeys(['id', 'user_id', 'created_at', 'latitude', 'longitude']);
The equivalent for the subquery:
SELECT MAX(created_at)
FROM coordinates
GROUP BY user_id
is
$data->sortByDesc('created_at') // we use sortByDesc to produce the same result as `MAX`.
->groupBy('user_id')
->pluck('0.created_at') // then to get the max value, just get the first array after grouping.
To achieve the select statement, we need to create a little macro, i've named it onlyKeys:
use Illuminate\Support\Arr;
Collection::macro('onlyKeys', function ($keys) {
return $this->map(function ($value) use ($keys) {
$tmpValue = (array) $value;
if (is_array($tmpValue)) {
$value = Arr::only($tmpValue, $keys);
}
return $value;
});
});
You can register the macro in your AppServiceProvider.php.
PS. Why you need to querying using Collection? Is that data not come from DB?
You want to collect array recursive
Unfortunately laravel does not have this feature:
you can write it on your own.
if you have helpers file you can write this method:
function recursive_collect($array){
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = recursive_collect($value);
$array[$key] = $value;
}
}
return collect($array);
}
Or You can implement macro in your AppServiceProvider:
\Illuminate\Support\Collection::macro('recursive', function () {
return $this->map(function ($value) {
if (is_array($value) || is_object($value)) {
return collect($value)->recursive();
}
return $value;
});
});
Hope this helps you

Resources