Laravel return specific model attribute - laravel

Let's say I have User Model. Each User has Pet model.
both have relationship setup correctly.
When I get the user data along with his pets, I do this:
return $this->with('pets');
but what if I want to return the pet name only with the user data?
I've been trying that:
return $this->with('pets.name');
Didn't work for me.

Model
Class User extends Model ()
{
...
public function pets()
{
return $this->hasOne('App\Model\Pet');
}
}
Controller or Repository or any other object
function getUserDetails (Request $request)
{
$userId = $request->get('id');
$findUserById = User::find($userId);
$fullName = $findUserById->pets->fullname;
}

You can do this way :
$users_with_pet_name = DB::table('users')
->join('pets', 'users.id', '=', 'pets.user_id')
->select('users.*', 'pets.name')
->get();
Check out joins section: https://laravel.com/docs/5.1/queries#joins

Related

How to call model in Controller request $request

I have a query in my model, which I want to call in my controller (request $request). It's working fine when the controller parameter is controller($id). But how to pass it in $request controller.
teacher Model with Query:
class teacher extends Model
{
public static function teacher($id)
{
return DB::table('teachers')
->leftjoin('religions', 'teachers.religion_id', '=', 'religions.id')
->leftjoin('areas', 'teachers.area_id', '=', 'areas.id')
->select('teachers.*','religions.*','areas.*')
->where('teachers.id',$id)
->first();
}
Controller which calls this model perfectly fine passing direct id:
public function report1($id)
{
$teacher = Teacher::teacher($id);
return View('teachers.report1' ,compact('teacher'));
}
Controller where I want to call it:
public function printreports(Request $request)
{
$teachers = $request->get('select2');
return view('teachers.report1',compact('teachers'));
}
Note: select2 contains teacher ids where I want to run model query.
Supposing you are have an array of ids in your select2 request param, probably easiest way is to change query at teacher model as follows:
use Illuminate\Support\Arr;
class teacher extends Model
{
public static function teacher($id)
{
return DB::table('teachers')
->leftjoin('religions', 'teachers.religion_id', '=', 'religions.id')
->leftjoin('areas', 'teachers.area_id', '=', 'areas.id')
->select('teachers.*','religions.*','areas.*')
->whereIn('teachers.id', Arr::wrap($id))
->get();
}
}

Trying to display eloquent data base from ID's

Hi I am trying to create a record base from ID of an order transaction.
I have here the ORDERS, CAMPANIES and CURRENCIES models.
Now I want the ORDER to get the ID from a URL Parameter, and then the companies should grab the company_id from Orders same with currency, I want to grab the currency_id from orders.
Here's what I came up so far:
public function create($order_id)
{
$order = Orders::find($order_id)->where('id', '=', $order_id)->get();
$company = Companies::where('id', '=', $order['company_id'])->get();
$currency = Currencies::where('id', '=', $order['company_id'])->get();
$banks = Banks::all('name','acronym','id')->get();
return view('orderPayments.create', compact('order'))
->with('company', $company)
->with('currency', $currency)
->with('banks', $banks);
}
currencies model
public function orderPayments()
{
return $this->hasMany('App\Orderpayments', 'id','currency_id');
}
Companies Model
public function orderPayments()
{
return $this->hasMany('App\Orderpayments', 'id','company_id');
}
Order Payments Model
public function company()
{
return $this->hasOne('App\Companies', 'id','company_id');
}
public function currency()
{
return $this->hasOne('App\Currencies', 'id', 'currency_id');
}
public function bank()
{
return $this->hasOne('App\Bank', 'id', 'currency_id');
}
How can I achieve it? thank you so much in advance!
UPDATE
I just applied #sandy's answer. I checked if the $order has a content so I echod the $order by doing this, {{ $order }} The return value is ok.
but when I calling the other attributes like $order->grandtotal, or $order->companies->comp_name the error is
If your relationship between your models is a One To Many relationship you should use belongsTo in your relations like this:
OrderPayment Model
public function company()
{
return $this->belongsTo('App\Companies','company_id');
}
public function currency()
{
return $this->belongsTo('App\Currencies','currency_id');
}
public function bank()
{
return $this->belongsTo('App\Bank', 'currency_id');
}
Also, the second parameter on the function should be your foreign key.
Answering your question:
If you want to access the relations of a given Order you could do this:
$order = Order::find($order_id);
$order->company; // this will return the company
$order->currency; // this will return the currency
If you want to display in your view:
{{$order->company->anyCompanyAttribute}}
Note:
You should name your models in SINGULAR like Currency, Company. Not in plural.
try like this
$order = Orders::with(['company','currency'])->where('id', '=', $order_id)->get();

Merging two queries into one using Eloquent

I have this two queries to display information in 3 tables Users, Comments, and Posts. so I made this function:
public function show($id)
{
$posts = Post::with(['comments'])->findOrFail($id);
$user = User::find($posts->user_id);
echo "<h1>".$posts->title.'</h1>';
echo "<h2>".$user->name.'</h2>';
foreach ($posts->comments as $comment) {
echo $comment->body.'<br>';
}
}
on this function I using two variable $posts and $user, can I merge this two variable using eloquests command like Post::with(['user','comments'])'? so I can use just $posts variable and use it like $posts->users->name to access user name.
i was trying using this way:
$posts = Post::with(['comments','users'])->findOrFail($id);
but when i echo the post it showing that the user was null:
{"id":1,"user_id":1,"title":"Oleh id 1","body":"ini adalah content","created_at":"2017-10-18 03:25:54","updated_at":"2017-10-18 03:25:54","comments":[{"id":1,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:50","updated_at":"2017-10-18 03:43:50"},{"id":2,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:53","updated_at":"2017-10-18 03:43:53"},{"id":3,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:54","updated_at":"2017-10-18 03:43:54"}],"users":null}
Here's my model if you need it. My post model:
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
public function users(){
return $this->belongsTo('App\User');
}
}
my Comment model
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
You’ll have an easier time sticking to Laravel’s conventions for naming relationships.
A Post has many Comments, which belong to a User. Given this set up:
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
You can then query a post’s comments and users like this:
$comments = $post->comments()->with('user')->get();
You could also eager-load the user relation on comments if you always wanted the user returned with a comment:
class Comment extends Model
{
protected $with = ['user'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Then your query would be simplified:
$comments = $post->comments;
Hope this helps you!!
What I am guessing is you want the list of all posts with the users. If relation is defined, try with the join
$posts = DB::table('posts')
->join('users', 'users.id', '=', 'posts.user_id')
->select('posts.*', 'users.name as user_name')
->where('posts.comments', '<>', NULL)
->get();
#NOTE: If you are using soft deletes you might wanna add where('posts.deleted_at', null)
After couple of days searching finally i got the answer, i can get merge the query like this:
$posts = Post::with(['comments','users'])->findOrFail($id);
but in the Post Model the function not "Users" but "User".

Laravel: Find all posts made by a user using name field

I want to fetch all posts made by a user by matching the name of the user from the route url using Eloquent
My User.php has relationship as follows
public function posts() {
return $this->hasMany('App\Post');
}
My Post.php model has following relationship:
public function user() {
return $this->belongsTo('App\User');
}
my route is like following:
Route::get('/users/{name}', 'UsersController#show');
I know if I want to fetch all posts by a user I need to do something like this
public function show($name) {
$user = User::find(1);
$posts = $users->posts()->get();
return view('users.show', compact('posts'));
}
but I want to find the user based on the name field in the database and not the id
I cant use ->posts() if I use where like Users::where('name', $name)->posts()->get(); , It throws error.
How do I fetch all posts of a user by matching his name in database with eloquent
You can use whereHas():
$posts = Post::whereHas('user', function($q) use($name) {
$q->where('name', $name);
})->get();
Or you can do this:
User::where('name', $name)->first()->posts()->get();
Or:
$user = User::where('name', $name)->first();
$posts = Post::where('user_id', $user->id)->get();
All these options will create two queries.

How to use one to many relation in Laravel?

I'm beginning to use Laravel Model relationship. But now I don't know how to used that relationship as below function
class Notification extends Model{
public function getNotification() {
return self::select('*')->join('users','users.id','=','Notification.n_user_id')->get();
}
}
Try this:
class User extends Model
{
/**
* Get the Notifications for the User.
*/
public function notifications()
{
return $this->hasMany('App\Notification');
}
}
But I see in your code that the foreign key field of User ID is named n_user_id you should changed it to user_id to link them
How to use:
$notifications = App\Post::find(1)->notifications;
foreach ($notifications as $notification) {
//
}
here is a useful Link in Laravel 5.2 Docs
Bonus:
You can also get the User of the notification:
class Notification extends Model
{
/**
* Get the User that owns the Notification.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
I have used the following way and hope it'd be helpful.
public function getNotification() {
$data = DB::table('users')
->join('Notification', 'users.id', '=', 'Notification.n_user_id')
->select('users.*', 'Notification.*')
->where('users.id', '=', 5)
->get();
return $data;
}

Resources