Laravel eloquent get all from one table and one from another - laravel

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()

Related

Eloquent Relationship belongsTo Return Error In Laravel 8

Let's assume, There Is two Table 'empData' & 'district'. 'empData' table contain 'id', 'name', 'empDistrict' ('empDistrict' contain the corresponding id of district) . and 'District' table contain 'id', 'name' of all districts.
Now I want to fetch the student's details including the district name. (Note: In the empDatatable, I contain only district id) How can I achieve this?
My Implementation
My District Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\EmpData;
class District extends Model
{
protected $guarded = [];
public function empdistrict(){
return $this->belongsTo(EmpData::class, 'empDistrict', 'id');
}
}
My EmpData Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::all();
return view('frontend.allusermindata',compact(['data']));
}
My Blade file where I show the data
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict()->name}}</p>
}
But I get this error
Trying to get property 'name' of non-object
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict->name}}</p>
}
Calling the method returns a BelonsTo class instance. Use laravel magic method by calling it as an attribute.
Further on this question, you'll have performance issues down the line, better load the data in the same query.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::with('empdistrict')->get();
return view('frontend.allusermindata', compact(['data']));
}

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');
})

Laravel relation one to many get results joined

I'm kinda lost one this one, I really can't find the problem, I have been watching a lot of questions all over the web but still can't seem to put this working properly.
I have two tables, the tabelaAngaricao table and the tabelaFotos table with a relationship of one-to-many, meaning that a tabelaAngariacao can have many tabelaFotos, and tabelaFotos as a angariacaoid(foreign key) so my tabelaAngariacao model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\TabelaFotos;
class TabelaAngariacao extends Model
{
protected $table = 'tabelaAngariacao';
public function TabelaFotos()
{
return $this->hasMany(TabelaFotos::class, 'angariacaoid');
}
}
and my tabelaFotos model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\TabelaAngariacao;
class TabelaFotos extends Model
{
protected $table = 'tabelaFotos';
public function TabelaAngariacao()
{
return $this->belongsTo('App\TabelaAngariacao');
}
}
What I want is to get all results joined by the angariacaoid, so in my controller I have:
public function index()
{
$results = DB::table('tabelaAngariacao')
->leftJoin('tabelaFotos', 'tabelaAngariacao.id', '=', 'tabelaFotos.angariacaoid')
->select('tabelaAngariacao.*')
->get();
}
Could someone help me on finding the problem? What is that I'm doing wrong?
You don't need to add select. Try following
$results = DB::table('tabelaAngariacao')
->leftJoin('tabelaFotos', 'tabelaAngariacao.id', '=', 'tabelaFotos.angariacaoid')
->get();
The above script will give you columns from both tables.
And probably you don't need to use DB::table, you can use Eloquent Queries instead, since you've defined your relationsips
You can try it by doing this.
$results = TabelaFotos::with('TabelaAngariacao')->get();
Here is how it works
$results = ModelName::with('relationship_in_model_name')->get();
Hope it works

Eloquent query: Filtering results based on relationship with other model

So I have two tables: posts and categories. It is a many-to-many relationship: A post has many categories and a category belongs to many posts.
Here are the models that describe their relationships:
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name', 'slug'];
public function posts()
{
return $this->belongsToMany('App\Post');
}
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
I want to get all posts that have a particular category: tips
Here is what I tried:
$tips = Category::where('name', 'Tips')->posts()->with('categories')->take(4)->get();
I don't know the level of ignorance in this query, but I honestly expected it to work. It didn't.
I'll appreciate any help.
It's really as simple as:
$tipsCategory = Category::where('name', 'tips')
->get();
$posts = $tipsCategory->posts;

Resources