laravel, displaying data from another table - laravel

I am trying to solve following problem:
I have 3 tables : passports ,statuses and passport_statuses, (passport_statuses table is the pivot table formed because of many to many relationship between passports and statuses. The model are like below:
passport model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
public function LatestStatus($query)
{
//dd($this->status[0]);
$allStatus=$this->status()->orderBy('updated_at')->first();
dd($allStatus);
//return $allStatus[0]->Status_Name;
//dd($allStatus[0]->attributes["Status_Name"]);
//dd($this->status()->get());
//return $allStatus[0]->attributes["Status_Name"];
//dd($allStatus);
}
}
Statuses model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport')->withTimestamps();
}
}
passportstatus model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PassportStatus extends Model
{
protected $fillable=[
'passport_id',
'statuses_id'
];
}
So I was able to save the passport status in the pivot table. Now I a trying to display the the latest status of that passport in the index page.
index page snapshot
saving passport details
my index view
#extends('admin.adminmaster')
#section('content')
<h2>Passport list </h2>
<a class="btn btn-primary" href="passport/create" role="button">+ Add New Passport</a>
<hr>
<table style="width:100%">
<tr>
<th>Name</th>
<th>Passport Number</th>
<th>Status</th>
</tr>
#foreach($passports as $passport)
<tr>
<td><h4> {{$passport->Full_Name}}</h4></td>
<td>{{$passport->Passport_Number}}</td>
{{--<td>{{dd($passport->status())}}</td>--}}
<td><a class="btn btn-warning" href="{{action('PassportController#edit', [$passport->id])}}" role="button">Edit</a>
<td><a class="btn btn-danger" href="{{action('PassportController#destroy',[$passport->id])}}" role="button"><span class="glyphicon glyphicon-trash"></span> Delete</a>
</td>
</tr>
#endforeach
</table>
#endsection
Controller
public function index()
{
$passports=Passport::latest()->get();
return view('admin.passport.index')->with('passports',$passports);
}
public function create()
{
$statuses=Statuses::lists('Status_Name','id');
return view('admin.passport.create')->with('statuses',$statuses);
}
public function store(Request $request)
{
$passport=Passport::create($request->all());
$passport->status()->attach($request->input('Status_Name'));
return redirect('admin/passport');
}
public function show($id)
{
$passports=Passport::findorFail($id);
return view('admin.passport.show')->with('passports',$passports);
}

You can add a function to your model that gets the latest status, and then you can use that function inside your view. This new function is not a new relationship, it is just a standard function.
class Passport extends Model
{
public function status() {
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
// this is not a relationship. just a standard method on the model.
public function latestStatus() {
return $this->status()->latest()->first();
}
}
In your view:
<td>{{ $passport->latestStatus()->Status_Name }}</td>

Related

Data can not be appears, database relation one to one Laravel

ErrorException
Trying to get property 'category_name' of non-object (View: D:\xampp\htdocs\e-catalog\resources\views\backend\pages\gmproducts.blade.php)
This is my blade code below.
<tbody>
#foreach($gmproducts as $no => $gm)
<tr>
<td>{{$no+1}}</td>
<td>{{$gm->type}}</td>
<td>{{$gm->gmcategories->category_name}}</td>
<td>{{$gm->gram}}</td>
<td>{{$gm->carat}}</td>
<td>#currency($gm->price)</td>
<td><a class="test-popup-link" href="{{url('p_goldmart/'.$gm->file)}}">Preview</a></td>
<td>
<i class="fa fa-edit"></i>
<i class="fa fa-trash-o"></i>
</td>
</tr>
#endforeach
</tbody>
This is my model Gmcategories & Gmproducts.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Gmcategories extends Model
{
protected $table = "gmcategories";
protected $fillable = ['category_name'];
public function gmproducts()
{
return $this->hasOne('App\Gmproducts');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Gmproducts extends Model
{
use SoftDeletes;
protected $table = "gmproducts";
protected $fillable = ['type', 'category_id', 'gram', 'carat', 'price', 'file'];
protected $dates = ['deleted_at'];
public function gmcategories()
{
return $this->belongsTo('App\Gmcategories');
}
}
This is my controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Gmproducts;
use App\Gmcategories;
use File;
class GmproductsController extends Controller
{
public function index()
{
$gmproducts = Gmproducts::orderBy('id', 'desc')->get();
$trash = Gmproducts::orderBy('deleted_at', 'desc')->onlyTrashed()->count();
return view('backend.pages.gmproducts', compact('gmproducts', 'trash'));
}
public function create()
{
$gmcategories = Gmcategories::all();
return view('backend.pages.create', compact('gmcategories'));
}
Just info, I just rename my model and controller. Does it have any effect? Thanks.
// Gmcategories model
public function gmproducts()
{
return $this->hasOne('App\Gmproducts', 'category_id');
}
// Gmproducts model
public function gmcategories()
{
return $this->belongsTo('App\Gmcategories', 'category_id');
}
Your BuildImage model should be
Get the source type of the Building Image.
public function type() {
return $this->hasOne('App\BuildingType',"id","source");
}
And BuildingType Model should be
Get the Building Image that owns the building type.
public function buildingImage()
{
return $this->belongsTo('App\BuildingImage',"source","id");
}

Call to undefined relationship [companies] on model [App\Models\Announcement]. How can I solve this

I have 2 tables : announcements and companies. company_id is a foreign key on announcement table.
I have controller set up like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\Company;
class AnnouncementController extends Controller
{
public function upcomingIssues()
{
$announcement = Announcement::orderBy('id','desc')->with('companies')->get();
return view('pages.upcoming-issues',compact('announcement'));
}
}
Announcement model is as follows:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Announcement extends Model
{
protected $table = 'announcements';
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
// Usage: $announcement->company
public function getCompanyAttribute()
{
return $this->companies->where('id','company_id')->get();
}
}
Company Model is follows
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'companies';
public function announcement()
{
return $this->hasMany(Announcement::class, 'company_id');
}
}
And Finally View table as follows:
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Company</th>
</tr>
</thead>
<tbody>
#foreach($announcement as $announce)
<tr>
<th>{{ $loop->iteration }}</th>
<td>{{ $announce->company }}</td>
</tr>
#endforeach
</tr>
</tbody>
</table>
when I try to access this page I get following message
"
Call to undefined relationship [companies] on model
[App\Models\Announcement].
"
You have to two ways to solve this issue.One is to change relationship name in Announcement model
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
to
public function companies()
{
return $this->belongsTo(Company::class, 'company_id');
}
or keep relationship name as it is and change in controller
public function upcomingIssues()
{
$announcement = Announcement::orderBy('id','desc')->with('companies')->get();
return view('pages.upcoming-issues',compact('announcement'));
}
to
public function upcomingIssues()
{
$announcement = Announcement::orderBy('id','desc')->with('company')->get();
return view('pages.upcoming-issues',compact('announcement'));
}
and also if you are using company as relationship name then change
public function getCompanyAttribute()
{
return $this->companies->where('id','company_id')->get();
}
to
public function getCompanyAttribute()
{
return $this->company->where('id','company_id')->get();
}

How to store multiple arrays in one query laravel

In view file is displayed players for each team in match.
here is code in view:
#foreach($match->homeTeam->players as $player)
<tr>
<th scope="row">{{$player->id}}</th>
<td class = "col-md-6" name = "fact[player]" value = "{{$player->id}}">{{$player->name}} {{$player->surname}}</td>
<td align="center" class= "col-md-2"><input class="form-check-input" type="checkbox" id="gridCheck"></td>
<td class = "col-md-2"><input id="minutes" type="integer" class="form-control" name="fact[minutes]"></td>
<td class = "col-md-2"><input id="goals" type="integer" class="form-control" name="fact[goals]"></td>
</tr>
#endforeach
So i need to store them in Match_facts table.
How to insert all in one query?
Match model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Team;
class Match extends Model
{
protected $fillable = ['round', 'league_id', 'home_team_id', 'away_team_id', 'match_date'];
public function leagues() {
return $this->belongsTo('App\League');
}
public function homeTeam() {
return $this->belongsTo('App\Team', 'home_team_id');
}
public function awayTeam() {
return $this->belongsTo('App\Team', 'away_team_id');
}
}
Player model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Player extends Model
{
public function team() {
return $this->belongsTo('App\Team');
}
}
In view addResult i have displayed Match(home_team and away_team)
and players of each team.
So i want to store match facts in table (match_facts) for each player of the team
Schema::create('match_facts', function (Blueprint $table) {
$table->id();
$table->uuid('match_id');
$table->uuid('player_id');
$table->integer('minutes')->nullable();
$table->integer('goals')->nullable();
$table->timestamps();
});
Founded solution:
$home_team_players=$match->homeTeam->players;
$away_team_players=$match->awayTeam->players;
$match_players = $home_team_players->merge($away_team_players);
foreach ( $match_players as $k => $p ) {
$data[] = [
'match_id' => $match->id,
'player_id' => $p->id,
'minutes' => $request['minutes'][$k],
'goals' => $request['goals'][$k]
];
}
Match_fact::insert( $data );
return view('admin.matches.index')->with('success','ADDED SUCCESSFULLY .');

How to display a column of different tables using the pivot table?

I am beginner to Laravel and now I am doing this project but I am stuck in this point for a couple days. Here is what I wish do, I would like to display the day and timeslot labels selected by the tutor!
here is my tables and their relationships
https://imgur.com/WMMwhHK
Day Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Day extends Model
{
protected $guarded = ['id', '_token'];
}
Timeslot Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Timeslot extends Model
{
protected $guarded = ['id', '_token'];
public function Tutor()
{
return $this->hasMany(Tutor::class);
}
}
Tutor_availability Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tutor_availability extends Model
{
protected $fillable = ['tutor_id', 'timeslot_id', 'day_id'];
protected $guarded = ['id', '_token'];
public function tutor()
{
return $this->belongsTo('App\Tutor');
}
public function day()
{
return $this->belongsTo('App\Day');
}
public function timeslot()
{
return $this->belongsTo('App\Timeslot');
}
}
tutor_availabilities Migration
public function up()
{
Schema::create('tutor_availabilities', function (Blueprint $table) {
// $table->bigIncrements('id');
$table->integer('day_id')->unsigned();
$table->foreign('day_id')->references('id')->on('days')->onDelete('cascade');
$table->integer('timeslot_id')->unsigned();
$table->foreign('timeslot_id')->references('id')->on('timeslots')->onDelete('cascade');
$table->integer('tutor_id')->unsigned();
$table->foreign('tutor_id')->references('id')->on('tutors')->onDelete('cascade');
$table->timestamps();
$table->primary(['day_id', 'timeslot_id', 'tutor_id']);
});
}
TutorController
public function index()
{
$tutors = Tutor::latest()->paginate(5);
$tutor_availabilities = Tutor_availability::all();
return view('tutors.index', [
'tutors' => $tutors,
'tutor_availabilities' => $tutor_availabilities
]);
}
View
<tr>
<th>Days</th> <th> Timings</th>
</tr>
<tr>
<td>
{{$tutor_availabilities->day->label}}
</td>
<td>
{{$tutor_availabilities->timeslot->label}}
</td>
</tr>
Put this in your Tutor_availability model
public function day()
{
return $this->belongsTo(Day::class);
}
public function timeslot()
{
return $this->belongsTo(Timeslot:class);
}
Then in controller
public function index()
{
$tutor_availabilities = Tutor_availability::all();
return view('tutors.index',
compact('tutor_availabilities')) ;
}
Then in view
<table>
#foreach ($tutor_availabilities as $tutor_available)
<tr><td>
{{$tutor_available->day->label}}
</td>
<td>
{{$tutor_available->timeslot->label}}
</td></tr>
#endforeach
</table>

cannot use hasOne relationship to place restriction

i have hasone relationship between models "member" and "loan". i throws "trying to get property of non object error
i have tried on hasMany and it all works but it has to be in hasOne, there is no restriction to stop multiple loan being issued to a member.
Member.php
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
protected $fillable=['name','address','phone'];
public function loan()
{
return $this->hasOne(Loan::class,'member_id','id');
}
public function savings()
{
return $this->hasMany(Saving::class,'member_id','id');
}
}
Loan.php
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $fillable = [
'amount',
'interest',
'status',
'member_id',
'loan_type_id',
'interest_type_id',
'loan_payment_type_id'
];
public function member()
{
return $this->belongsTo(Member::class,'member_id','id');
}
}
member.blade.php
<td>{{$member->name}}</td>
<td>{{$member->address}}</td>
<td>{{$member->phone}}</td>
<td>
Delete
Edit
</td>
<td>
{{$member->loan->amount}}
</td>
Maybe all of your member don't have a loan. that's why error shown, Try to check before echo,
<td>
#if($member->loan) // add this line code
{{ $member->loan->amount }}
#endif // add this line code
</td>
Try
{{$member->loan['amount']}}

Resources