How can i get article owner user_id and save to notifiable_id field - laravel

How can i get article owner user_id and save to notifiable_id field
Suppos
$articlecomment = $article_owner_id
My code:
$articlecomment = new Article_comment();
$articlecomment->user_id = Auth::user()->id;//Comment by user id
$articlecomment->article_id = $request->articleid;
$articlecomment->comment = $request->comment;
$articlecomment->save();
auth()->user()->notify(new ArticleNotification($articlecomment));
//$articlecomment->user()->notify(new ArticleNotification($articlecomment));
Database Screenshot
i want article_owner_user_id on notifible_id field
enter image description here

Solved
$articlecomment->save();
$article = Article::where('id','=',$request->articleid)->first();
if($article->user_id != Auth::User()->id){
$article->user->notify(new ArticleNotification($article));
}

This is database i need article_owner_id on notifible_id field click here to see screenshot

If you have a relationship set up for your Article_comment and Article models, you can access the "Article Owner" through the relation.
For example, define a relation for your "Article" model inside your Article_comment class (assuming Article is the name of your model):
class Article_comment extends Model {
....
public function article() {
return $this->hasOne('App\Article', 'id', 'article_id')
}
....
}
Once you have that set, you can access your relation (and subsequent properties) like so (assuming article_owner_id is a property of your Article model):
$articlecomment->article->article_owner_id
Edit:
Whichever user you call notify on will notify that user. So to notify the article owner, you will need to get the user of the article and call notify from that instance (rather than the auth user). If you set up a relation to the user on your Article class, you can simply call notify from that, or get the user from the article_owner_id and call notify.
Example:
$user = User::where('id', '=', $articlecomment->article->article_owner_id)->first();
$user->notify(new ArticleNotification($articlecomment));
With a relation set on your Article class, you could instead call notify like this:
$articlecomment->article->user->notify(new ArticleNotification($articlecomment));
For more info on Eloquent relationships, see https://laravel.com/docs/5.6/eloquent-relationships#introduction

Related

Repleace relationship by name of this relationship

I have a model User with fileds like - colorhair_id, nationality_id, etc. Of course I have a relationship to other model. Problem is that I want to return nationality from User i must do that:
User::find(1)->colorhair->name
In next time I need to use
User::find(1)->nationality->name
It works but it's not look professional and it's dirty. How can I change query or something else to return object with repleace field like nationality_id to nationality with name of that. Any idea?
You can use Laravel Mutators. Put below two functions into the User model
public function getHairColorNameAttribute(){
return $this->colorhair->name
}
public function getNationalityNameAttribute(){
return $this->nationality->name
}
Then when you simply access it.
User::find(1)->hair_color_name;
The next time
User::find(1)->nationality_name;
If you want to get these values by default use $append in the model. Put the following line to the top of the User model
protected $appends = ['hair_color_name','nationality_name'];
Note: In laravel 9 mutators little bit different from the above method.
Bonus Point :
if you access values in the same scopes don't use find() method in each statement.
$user = User::find(1);
then
$user->hair_color_name;
$user->nationality_name;

How to eloquent relationship with multiple results

Problem
I have two classes, Users & Posts. A user "hasMany" posts and a post "belongTo" a user. But when I call "User::all()" it doesn't automatically pull the users posts for obvious reasons, because if my user had relations to 100 different tables pulling all users would start to become pretty chunky.
Question
Is there a way to pull all users and all user->posts in one or few lines of code without going through a foreach loop?
I know i can use a mutator but the problem I have is my field is called user_id and i have tested it with this code:
public function getUserIdAttribute($id)
{
return User::find($id);
}
But it will replace "user_id" field value with a user object, Id rather have it set to its own "temporary user" field within the result. I'm trying to find best practice!
Thank you in advance.
What you're looking for is called Eager Loading
Inside your post model :
class Post extends Model
{
protected $table='posts';
public $primaryKey='id';
public function user(){
return $this->belongsTo('App\User','user_id');
}
}
now you want to get post with user use below code :
$posts=Post::with('user')->get();
inside your user model :
class User extends Model
{
public function posts(){
return $this->hasMany('App\Model\Post');
}
}
now you want to get a user with all posts :
$user=User::where('id',$id)->first();
$user_posts=$user->posts;

Backpack laravel how show in the same view tables related

Hello how are you all? i enter here because i not found the reply in the documentation, i have a relation 1-1 in my ddbb, is there some way to show this linked in the same view crud? Then with a button that open the eloquent model related in a dialog. Or something in this way without load in. New windows reload, or by example show the details of the parent eloquent and show just in the line down tabulated the children table, there are some. Example that how to do this?
If I understood correctly you ask if something like this is possible?
Controller:
$blogpost= Blogpost::where('id', '=', $id)
->with('comments')
->with('reactions')->first();
return view('blogpost_single','blogpost' => $blogpost);
Then in your view you can access the blogpost variable itself:
Blog title: {{$blogpost->title}}
and the children
Blog comment 1: {{$blogpost->comments[0]->text}}
Blog comment 2: {{$blogpost->comments[1]->text}}
Example:
In Users Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
If you want get one user you can try:
User::find(1)->phone
If you want get all users with phone of this user you can try
User::with('phone')->all();
After you see result object and let see it

Create multiple objects from api post in laravel

Im at a bit of a loss. I have an api that will create a user upon a request. This is done no problem.
I also want to create another controller action or add to my current action the ability to create an address for the same user.
Is there an easy way to do this? Or should I stick to the
$user = new User(Input::all());
$user->save();
$address = new Address(Input::all());
$address->save();
You should set up relationships between your User and Address model - http://laravel.com/docs/eloquent#relationships and use associate/sync() to connect the dots.
This is a relationship problem. An address to a user will most likely be One-to-One (i.e., each Userhas a unique Address). A User might have an Address, but an Address must have a User. So in essence, the Address belongs to User.
Create two tables users and addresss, and add user_id to the address table as a column.
Then you define your relationships:
// In your User.php model
public function address()
{
return $this->hasOne('Address');
}
// In your Address.php model
public function user()
{
return $this->belongsTo('User');
}
Note when you use the correct notation, you can just define the model name, and not specify the pivot column. That is why I have defined the class addresss with an extra 's' to make it plural. I personally don't care about the spelling and rather Laravel take care of everything. Otherwise read the documentation on how to define the pivot column
Then you can use associate easily:
$user = new User();
// Fill $user however you want
$address = new Address();
// Fill $address however you want
$user->associate($address);
$user->save();
I was able to figure it out!
I wound up utilizing the Ardent package to help me validate my models before they hit the save method.
if my models didnt validate i will return all the errors to the user.
If they did validate my models would be created.
As for the association I am using the has many relation ship on the User and belongs to on the Address.
I used the following to save the address to the user
$address = $user->address()->save($address);
however I could only preform this after the initial user object was saved.
Thanks for all the responses guys they lead me in the right direction!

Laravel 4: How to add more data to Auth::user() without extra queries?

I'm rather new to Laravel 4 and can't seem to find the right answer, maybe you can help:
A User in our application can have many Accounts and all data is related to an Account, not a User. The account the User is currently logged into is defined by a subdomain, i.e. accountname.mydomain.com.
We added a method account() to our User model:
/**
* Get the account the user is currently logged in to
*/
public function account()
{
$server = explode('.', Request::server('HTTP_HOST'));
$subdomain = $server[0];
return Account::where('subdomain', $subdomain)->first();
}
The problem is that there is always an extra query when we now use something like this in our view or controller:
Auth::user()->account()->accountname
When we want to get "Products" related to the account, we could use:
$products = Product::where('account_id', Auth::user()->account()->id)->get();
And yet again an extra query...
Somehow we need to extend the Auth::user() object, so that the account data is always in there... or perhaps we could create a new Auth::account() object, and get the data there..
What's the best solution for this?
Thanks in advance
Just set it to a session variable. This way, you can check that session variable before you make the database call to see if you already have it available.
Or instead of using ->get(), you can use ->remember($minutes) where $minutes is the amount of time you wish to keep the results of the query cached.
You should take a look at Eloquent relationships : http://laravel.com/docs/eloquent#relationships
It provides simple ways to get the account of a user and his products. You said that a user can have many accounts but you used a first() in your function I used a hasOne here.
Using Eloquent relationships you can write in your User model:
<?php
public function account()
{
// I assume here 'username' is the local key for your User model
return $this->hasOne('Account', 'subdomain', 'username');
}
public function products()
{
// You should really have a user_id in your User Model
// so that you will not have to use information from the
// user's account
return $this->hasMany('Product', 'account_id', 'user_id');
}
You should define the belongsTo in your Account model and Product model.
With Eager Loading you will not run a lot of SQL queries : http://laravel.com/docs/eloquent#eager-loading
You will be able to use something like
$users = User::with('account', 'products')->get();
To get all users with their account and products.
I think this is a good example for the purpose of Repositories.
You shouldn't query the (involved) models directly but wrap them up into a ProductRepository (or Repositories in general) that handles all the queries.
For instance:
<?php
class ProductRepository
{
protected $accountId;
public function __construct($accountId)
{
$this->accountId = $accountId;
}
public function all()
{
return Product::where('account_id', $this->accountId)->get();
}
}
//now bind it to the app container to make it globaly available
App::bind('ProductRepository', function() {
return new ProductRepository(Auth::user()->account()->id);
});
// and whenever you need it:
$productRepository = App::make('ProductRepository');
$userProducts = $productRepository->all();
You could group the relevant routes and apply a filter on them in order to bind it on each request so the account-id would be queried only once per repository instance and not on every single query.
Scopes could also be interesting in this scenario:
// app/models/Product.php
public function scopeCurrentAccount($query)
{
return $query->where('account_id', Auth::user()->account()->id);
}
Now you could simply call
$products = Product::currentAccount()->get();

Resources