Unable to do laravel relationships using laravel 5.5 - php

I am facing issue regarding storing ids and display their values from two different table i have 1 table business_master and other table is page_master i have combine business_name column with page_url column which are available on page_master table if i add my business and page first time its successfully combine these two values as one business can have many pages and if i only add page 2nd time i am unable to see business_url with page_url column.
My Page Model:
class PageList extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id', 'page_url', 'page_name'];
public function business()
{
return $this->hasOne('App\Business','business_id');
}
}
and in my view:
<td>{{optional($value->business)->business_url}}.spikesales.io/{{$value->page_url}}</td>
This is my first time out if i add business_url and page_url
hussain.spikesales.io/house
and then if i add only page the out put is something like that
.spikesales.io/hello
one business can have many page it should attach business_ url also but i am unable to find solution:
Any help will be highly appreciated!
public function pageListHere()
{
$list = PageList::all();
return view('page-list',compact('list'));
}

You have to change your controller code like this:
$list = PageList::select('*');
$list->with(
array('business'=>function($query){
$query->select('*');
}));
$pageList = $list->get();
return view('page-list',compact('pageList'));
The varialbe $pageList will be having all the rows of that table along with related Business table rows.

Related

Get data from multiple sql tables using eloquent with laravel

What i want to achieve?
Show user which pacts he is following.
What I am trying
I have designed two tables which are 'pacts' & 'pacts_follwers'
Table 'pacts' has the details of all the pacts
Table 'pacts_follwers' has details of users following a particular pact.
These links will give you the images of both the tables
For Schema Refer Images
So how to get pacts that user is following.
What I have tried?
Sql Query
SELECT pacts.*, (SELECT pactsid FROM pacts_follwers WHERE pacts.id = pacts_follwers.pactsid
and pacts_follwers.userid = 2 ) as pactID FROM `pacts`
Sql query Result
This query will give pactId some value, where the value is null means the user is not following that pact. If this is the solution then i would need Eloquent for this which i am unable to make.
1st table pacts
id
title
about
created_at
updated_at
pactsImage
2nd table pacts_follwers
id
pactsid
userid
created_at
updated_at
Controller Code
$pacts = DB::select("SELECT pacts.*, (SELECT pactsid FROM pacts_follwers WHERE pacts.id =
pacts_follwers.pactsid and pacts_follwers.userid = ".Auth::id()." ) as pactID FROM `pacts`");
You need to setup hasManyThrough relationship for User and Pact.
class User extends Model {
public function pacts() {
return $this->hasManyThrough(
Pact::class,
PactFollower::class
'userid',
'pactsid'
);
}
}
I don't fully understand if you want to achieve "get user's all pacts" or "if pact is followed by user". Either way, you need to setup related relationships.
Or really simple (and not efficient way)
class Pact extends Model {
public function followers() {
return $this->hasMany(PactFollower::class, 'pactsid')
}
}
Now you can use something like
$userIdsForPact = Pact::followers()->pluck('userid');
if ($userIdsForPact->has($user->id)) {
// your operation
}
Edit: For "if pact is followed by user", you need to setup belongsToThrough relationship. It doesn't come out of the box with Laravel but staudenmeir/belongs-to-through package should serve you well.
After setting the relationship properly, you can use something like this.
Pact::with('user')->get();
Or add some methods in your Pact model:
public function followedByUser($user) {
return $this->users->has($user);
}

Copying Data from table to another table and applying one to many relationship

This is my Report Model
protected $fillable = [
'site_url',
'reciepients',
'monthly_email_date'
];
public function site()
{
return $this->belongsTo('App\Site');
}
This is my Site Model
public function report()
{
return $this->hasMany('App\Report');
}
This is my ReportController
public function showSpecificSite($site_name)
{
$records = DB::table('reports')
->select('email_date','url','recipient')
->whereHas('sites', function($query){
$query->where('site_name',$site_name);
})
->get();
return view('newsite')->with('records',$records)
->with('site_name',$site_name);
}
My Controller is not yet working as well.
The thing is I would like to copy all the three files from sites table to reports table.
Is it possible in insertInto ?
My code on ReportController shows you that I'm selecting data from reports table but I am the one who puts data to reports table to see the output but it is not yet working because of the it cant reach out the value of site_name even though I already put a relationship between the two tables.
You're not actually using Eloquent in your controller you're just using the Query Builder (DB). This will mean that you don't have access to anything from your Eloquent models.
Try:
$records = \App\Report::whereHas('site', function($query) use($site_name) {
$query->where('site_name', $site_name);
})->get(['id', 'email_date', 'url', 'recipient']);
I've added id to the list of columns as I'm pretty sure you'll need that to use whereHas.
NB to use a variable from the parent scope inside a closure you need to pass it in using use().

One to many relationship in laravel extracting the latest timestamp

I have a one to many relationships in the database, and I am trying to extract the latest. The table names are notification and alertFrequency, they have models for each. I want to write a query that will get me the latest time stamp associated to a specific website in the notifications table. The alertFequency table has only 2 columns namely notification_id and created_at. the following are my model notification modl
class Notification extends Model
{
protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
public function alertFrequencies(){
return $this->hasMany('App\AlertFrequency');
}
// trail versions
public function alert(){
$items = AlertFrequency::select('alertFrequencies.created_at')//Any column you want to fetch
->join('notifications', 'notifications.id', '=', 'alertFrequencies.notification_id')
->orderBy('alertFrequencies.created_at','desc')
->first();
if($items == null){
return null;
}
return $items->created_at->toDateTimeString();
class AlertFrequency extends Model{
protected $table = 'alertFrequencies';
public function notification(){
return $this->belongsTo('App\Notification');
}
}
inside the notification model i wrote a function that is expected to extract the data(i.e the latest time stamp of a specific website in the notification table) more over the notification_id is a foreign key in the alertFrequency table. the alert function is as follows
public function alert(){
$alert_timestamp = AlertFrequency::with('notification')->select('created_at')->orderBy('created_at','desc')->first();
//$alert_timestamp=$alert_timestamp->created_at->toDateTimeString();
if($alert_timestamp==null){
return false;
}
return $alert_timestamp;
}
it is returnning created_at time stamp but not the latset related to a specific website. i would apperciate your help?
in the database i have two websites added one at 12:18 and the second ata 12:24..... sorry i dont know how i can post the database here.
Directly You can not apply orderBy() on relation you need to use join()
Just try this. Hope it helps
$alert_timestamp = AlertFrequency::select('alertFrequencies.created_at')//Any column you want to fetch
->join('notification', 'notification.notification_id', '=', 'alertFrequencies.notification_id')
->orderBy('alertFrequencies.created_at','desc')
->get();

How can i get all posts by a particular user in Laravel?

Try to get all post's by a user in application and show in a table with corresponding column , i tried with this way but showing exception : " Trying to get property of non-object " , how to solve it ?
public function usersPost(){
$uid = \Auth::user()->id;
$posts = DB::table('posts')->('user_id',$uid);
}
Here two table posts and users and user_id is foreign key of posts table .
Laravel allows you to relate models to each other. For instance, you can relate your Post model to your User model like this.
class User extends Eloquent {
public function posts() {
return $this->hasMany('Post');
}
}
After specifying that the User has many posts through a One-to-Many relationship, you can then simply call all of your user's posts.
$posts = User::find(user_id)->posts;
public function usersPost() {
$posts = DB::table('posts')->where('user_id', auth()->id())->get();
}
You need a where clause like this:
$posts = DB::table('posts')->where('user_id', $uid)->get();

How to return model rows where id is equal to id on other table with relations in laravel?

For example I have:
// Returns all projects
$projects = Projects::all();
To return categories, belonging to project, I use relationships and can do something like:
foreach($projects as $project) { ...show $project->categories... }
I need only specific projects, which are followed by specific user. On my projects_followers table I have user_id and project_id.
To retrieve projects which were followed I have this peace of code:
$projects = Project::rightJoin(DB::raw('(select * from projects_followers group by project_id) projects_followers'),'projects_followers.project_id','=','projects.id')->get();
// Note: This code doesn't include specifuc user_id.
It does retrieve specific rows, but the problem with this code is that laravel relationhips dont work on them. For example $project->categories return empty.
// Relationship
public function categories()
{
return $this->belongsToMany('App\Category');
}
How do I retrieve my model specific rows and make relationships to work?
Actually your question is:
How do I get projects liked/followed by Auth/Logged in User ?
Unfortunately you described it in such a way that it looks something else, anyways. Lets try to find the solution and for this I would like to use something like this:
$projects = Auth::user()->favorite_projects;
So how we can implement this to work, first of all the User Model should contain the method favoriteProjects so lets create it:
public function favoriteProjects()
{
return $this->belongsToMany(
'App\Project',
'projects_followers', // This table already exists as you mentioned
'user_id',
'project_id'
);
}
That's it. You will be able to load the projects followed by the current user and other relationship methods will work on every single project as well.
My workaround:
// I don't know how to create empty collection, so impossible conditions here.
$projects = Project::where('id', 0)->get();
$follows = DB::table('projects_followers')->where('follower_id', Auth::user()->id)->get();
foreach($follows as $follow) {
$project = Project::where('id', $follow->project_id)->first();
$projects = $projects->add($project);
}

Categories