Laravel create simple RelationShip and get User data from other table - laravel

i'm created simple RelationShip from two table as User and Merchant :
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
public function merchant()
{
return $this->hasMany('App\Merchant');
}
}
in App\Merchant is:
class Merchant
{
protected $table = 'merchand_web_service';
protected $fillable = ['agent_unique_id', 'agent_company_name', 'agent_company_logo'];
public function user()
{
return $this->belongsTo('App\User');
}
}
and my Migration file is:
class MerchandWebService extends Migration
{
public function up()
{
Schema::create('merchand_web_service',function(Blueprint $table){
$table->increments('id');
$table->string('customer_key','50');
$table->string('company_name','50');
$table->string('company_logo','100');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('merchand_web_service');
}
}
now i want to access User data on Merchant table on database by this code on Controller :
$all_records = Merchant::with('user')->orderBy('id', 'DESC')->paginate(50);
Unfortunately i get this error:
Call to undefined method app\Merchant::with()

You miss here extending Merchant class from basic Model.
It should be:
class Merchant extends Model
instead of
class Merchant
You should also look use exact same case for namespaces. Looking at error you use app\Merchant instead of App\Merchant

Related

One to Many Relationship with Pivot Table and fetch related data using the with method

In Laravel 5.5 application, I have a model called Meeting and a model called Room.
Both models have a many-to-many relationship through a pivot table called MeetingSchedule.
The MeetingSchedule table has a column called schedule_by which is a foreign key to the user_id column in the User table.
I want to get the email address of the user who scheduled the meeting, when I fetch the meeting details with schedules() function of Meeting model.
I have tried the following code but it does not work:
class Meeting extends Model {
protected $table = 'Meetings';
protected $primaryKey = 'meeting_id';
protected $fillable = ['topic', 'description', 'participants_count'];
public function schedules() {
return $this->belongsToMany('App\Room', 'MeetingSchedule', 'meeting_id', 'room_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class Room extends Model {
protected $table = 'Rooms';
protected $primaryKey = 'room_id';
protected $fillable = ['name', 'location', 'capacity'];
public function schedules() {
return $this->belongsToMany('App\Meeting', 'MeetingSchedule', 'room_id', 'meeting_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class MeetingSchedule extends Pivot {
protected $table = 'MeetingSchedule';
protected $primaryKey = 'schedule_id';
public function scheduledBy() {
return $this->belongsTo('App\User', 'scheduled_by', 'user_id');
}
}
class User extends Authenticatable {
protected $table = 'User';
protected $primaryKey = 'user_id';
protected $fillable = ['username', 'email'];
public function meetingScheduledBy()
{
return $this->hasMany('App\MeetingSchedule', 'scheduled_by', 'user_id');
}
}
function getMeetingWithRelatedData($meetingId) {
return Meeting::where('meeting_id', $meetingId)
->with(['schedules'])
->first();
}

Laravel nested cross database relation

Why set connection does not work in nested relation?
Follower.php
class Follower extends Model {
$connection = 'followers';
public function details() {
return $this->belongsTo(User::class, 'user_id');
}
}
User.php
class User extends Model {
$connection = 'users';
protected $withCount = ['notifications'];
public function notifications() {
return $this->setConnection('followers')->hasMany('App\Models\Notifications');
}
}
and the query:
Follower::query()->where('user_id', 1)->with('details')->get();
and it throws :
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'users.notifications' doesn't exist (SQL: select ` ....
But when I try this it works very well
User::with('notifications')->find(1);
Update
Notification.php
class Notification extends Model
{
protected $fillable = [
'user_id',
'builder',
'notification_type',
'comment_id',
'read_at'
];
}
This is a known issue with laravel since 2018, for more information see this thread , also there is a open pull request to fix this issue and will get fixed till next release
for now you can use hoyvoy/laravel-cross-database-subqueries package
install package using this
composer require hoyvoy/laravel-cross-database-subqueries
Follower.php
use Hoyvoy\CrossDatabase\Eloquent\Model;
class Follower extends Model {
$connection = 'followers';
public function details() {
return $this->belongsTo(User::class, 'user_id');
}
}
User.php
use Hoyvoy\CrossDatabase\Eloquent\Model;
class User extends Model {
$connection = 'users';
protected $withCount = ['notifications'];
public function notifications() {
return $this->setConnection('followers')->hasMany('App\Models\Notifications');
}
}
for every model you have add the default protected $connection

retrieve data from multiple table using ajax

this is posts table:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('prf_id')->unsigned();
$table->foreign('prf_id')->references('id')->on('profiles')->onDelete('cascade');
$table->longText('status');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
this is comments table:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('prf_id')->unsigned();
$table->foreign('prf_id')->references('id')->on('profiles')->onDelete('cascade');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->longText('comment');
$table->integer('like')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('comments');
}
}
this post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table='posts';
protected $fillable = ['status'];
protected $hidden = [];
public function profile(){
return $this->belongsTo('App\Profile', 'prf_id');
}
public function user(){
return $this->belongsTo('App\User');
}
public function comment(){
return $this->hasMany('App\Comment');
}
}
this is Comment model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table='comments';
protected $fillable = ['comment','like'];
protected $hidden = [];
public function post(){
return $this->belongsTo('App\Post', 'post_id');
}
public function profile(){
return $this->belongsTo('App\Profile', 'prf_id');
}
public function user(){
return $this->belongsTo('App\User');
}
}
In blade page i can easilly retrieve all comments of a particular post like :
suppose i got $posts as post
#foreach ($post->comment as $comment)
{{$comment->comment}}
but in ajax how could i do this
suppose i return response()->json($posts);
any suggestion ?it will help me a lot
You don't have to write response()->json($posts), You can simply return $posts and Laravel will convert response to JSON automatically.
About Your exact problem: When querying $posts in controller, add with('comment') execution, like: $posts = Post::with('comment')->get() it will then return posts with comment prefetched.
It's Laravel's eager loading, You can read more about it here: https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

Laravel 5.1 Eloquent Relationship

Is there anyone can suggest from the eloquent relationship that I have based on the screenshot and model setup?
Model setup:
class Leaves extends Model
{
protected $table = 'leaves';
protected $fillable = [
'leave_type',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
class LeaveType extends Model
{
protected $table = 'leave_type';
protected $fillable = ['type_name'];
}
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function leave()
{
return $this->hasMany('App\Leaves');
}
}
Currently I only able to get the leaves detail but need to retrieve the leave_type's type_name based on
$user = User::oldest('name')->get();
foreach ($users as $user) {
$user->leave()-get();
}
in your Leave model you would have
function type() {
return $this->hasOne(App\LeaveType);
}
in your LeaveType you should reciprocate
function leave() {
return $this->belongsToMany(App\LeaveType);
}
and in your controller:
$user = User::oldest('name')->with('leave', 'leave.type')->get();
dd($user->leave->type);
Leaves model:
class Leaves extends Model {
protected $table = 'leaves';
protected $fillable = [
'leave_type',
'user_id'
];
public function User()
{
return $this->belongsTo('App\User');
}
public function LeaveType()
{
return $this->belongsTo('App\LeaveType');
}
}
LeavesType model:
class LeaveType extends Model {
protected $table = 'leave_type';
protected $fillable = ['type_name'];
public function Leaves()
{
return $this->hasMany('App\Leaves');
}
}
User model:
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function Leaves()
{
return $this->hasMany('App\Leaves');
}
}

Laravel Eloquent hasManyThrough Relationship, SELECT without

I have 3 entities:
Company, User, Ticket
I need to select ALL companies that have no tickets, how can I manage that using Eloquent?
this are the relationships
class Company extends Eloquent {
protected $table = 'companies';
protected $fillable = array('name', 'priority', 'shortname', 'color');
public function users() {
return $this->hasMany('User', 'companies_id');
}
public function tickets() {
return $this->hasManyThrough('Ticket', 'User', 'companies_id', 'from_users_id');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
public function company() {
return $this->belongsTo('Company', 'companies_id');
}
public function tickets() {
return $this->hasMany('Ticket', 'from_users_id');
}
}
class Ticket extends Eloquent {
protected $table = 'tickets';
public function user() {
return $this->belongsTo('User', 'from_users_id');
}
}
It is not documented but Company::doesntHave('tickets') should work.
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Builder.html#method_doesntHave

Resources