I have two tables; Students and Grade. Students contains foreign key grade_id referencing Grade.
For viewing students, I have used following code;
Controller:
public function viewStudent()
{
$students=Student::all();
return $students('grade_id');
$grade = Grade::find($id, ['id', 'grade_name']);
return view('students.view',compact('students'));
}
View:
<tbody>
#foreach($students as $student)
<tr class="info">
<td>{{$student->first_name}}</td>
<td>{{$student->middle_name}}</td>
<td>{{$student->last_name}}</td>
<td>{{$student->grade_id}}</td>
</tr>
#endforeach
</tbody>
Model:
class student extends Model
{
//
protected $fillable = ['first_name','middle_name','last_name','grade_id'];
}
It shows grade_id as i have called it. But I want grade_name instead of that. Can anyone help me?
First you need to define a relation to Grade in your student model:
class student extends Model
{
public function grade() {
return $this->belongsTo(Grade::class);
}
}
Then you should be able to eagerly load grades for students with
$students = Student::with('grade')->get();
and access student's grade name with
$student->grade->name
In Model
class student extends Model
{
protected $fillable = ['first_name', 'middle_name', 'last_name', 'grade_id'];
public function grade()
{
return $this->belongsTo('Grade');
}
}
In Controller
$students = Student::with('grade')->get();
In View
#foreach ($students as $student)
$studentGradeName = $student->grade->name;
#endforeach
Related
I have an issue, when I delete a contractor that relate to that one residence, there will be an error something like trying to get property name in this line in index view <li>Contractor: {{$res->contractor->name}}. I want to make it possible by deleting the contractor, then the contractor field in residence view could be empty or null. And this can be vice versa. How can I do that? Here is my model.
Residential.php
class Residential extends Model
{
protected $fillable = ['name','res_code','postcode','city','state','image','contractor_id'];
public function contractor()
{
return $this->belongsTo(Contractor::class);
}
public function buyer()
{
return $this->hasMany(Buyer::class);
}
}
Contractor.php
class Contractor extends Model
{
protected $table = 'contractors';
protected $fillable = ['name','address','phone_no','email','avatar'];
public function residential()
{
return $this->hasMany(Residential::class);
}
public function users()
{
return $this->morphMany(User::class, 'typable');
}
}
Here is my controller.
ResidentialController.php
class ResidentialController extends Controller
{
public function index(Request $request)
{
$contractor = Contractor::find($request->id);
$residential = Residential::all();
return view('residentials.index',compact('residential','contractor'));
}
ContractorController.php
public function index(Request $request)
{
$residential = Residential::find($request->id);
$contractor = Contractor::all();
return view('admins.contractors.index', compact('residential', 'contractor'));
}
And here is my view.
residentials\index.blade.php
#foreach($residential as $res)
<div class="panel-body">
<ul class="list-unstyled list-justify">
<li>ID: {{$res->id}}</li>
<li>Code: {{$res->res_code}}</li>
<li>Postcode: {{$res->postcode}}</li>
<li>City: {{$res->city}}</li>
<li>State: {{$res->state}}</li>
<li>Contractor: {{$res->contractor->name}}
</ul>
</div>
#endforeach
contractors\index.blade.php
<table class="table table-hover" id="contractor-table">
<tr>
<th>ID</th>
<th>Company</th>
<th>Phone No</th>
<th>Email</th>
<th>Residence</th>
<th>Action</th>
</tr>
#foreach($contractor as $cont)
<tr class="contractor{{$cont->id}}">
<td>{{$cont->id}}</td>
<td>{{$cont->name}}</td>
<td>{{$cont->phone_no}}</td>
<td>{{$cont->email}}</td>
<td>{{$cont->residential->pluck('name')->implode(', ')}}</td>
#endforeach
</table>
I hope there is someone can understand my problem and can help me.
You have to use LEFT JOIN in your query.Using of it you will automatic receive NULL value.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching join predicate.
Reference link : https://www.tutorialspoint.com/sql/sql-left-joins.htm#:~:text=Advertisements,column%20from%20the%20right%20table.
Can anyone help me how to display the product name? I have productquantity stored in my purchase record and now I want to display the product name in productquantity record.
I have 3 Tables
Purchaserecord
id
purchasenumber
prodquantityid
Productquantities
id
prod_id
Product
id
productname
Controller:
public function createpurchase(Request $request)
{
$purchasenumber = $request->purchasenumber;
$dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)->with('productquantity')->get();
return view('admin.createpurchase',compact('purchasenumber', 'dataPurchaseRecord'));
}
View:
#forelse($dataPurchaseRecord as $Request)
<tr>
<td> <a class="name">{{$Request->productquantity->prod_id}}</a></td>
<td><em class="productprice">{{$Request->quantity}}</em> </td>
<td style="width:100px;" class="td-actions"> </i>Remove </td>
</tr>
#empty
<tr><td colspan='4'><em>No Data</em></td></tr>
#endforelse
Model:
public function product()
{
return $this->belongsTO('App\Product', 'prodquantityid', 'id');
}
{{$Request->productquantity->prod_id}} should be display the product name instead of the id
How can I build the model and view on this?
You could define your models as
Class Purchaserecord extends Model{
public function productquantity()
{
return $this->belongsTo('App\Productquantities', 'prodquantityid');
}
}
Class Productquantities extends Model{
public function product()
{
return $this->belongsTo('App\Product', 'prod_id');
}
public function purchaserecords()
{
return $this->hasMany('App\Productquantities','prod_id');
}
}
Class Product extends Model{
public function productquantities()
{
return $this->hasMany('App\Productquantities','prod_id');
}
}
Now eager load your data like
$dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)
->with('productquantity.product')
->get();
In loop you access product object as $Request->productquantity->product->name
Eloquent: Relationships
I am here stuck in this issue:
The issue is i want to load the 2 column values from two different tables in same view and view in which i want to show the values is already having controller method:
I will explain you with my code:
My controller method:
public function pageListHere()
{
$list = PageList::all();
return view('page-list',compact('list'));
}
this is my method using PageList model table name is (page_master).
And my view is:
#foreach($list as $key => $value)
<tr>
<input type="hidden" id="rwid" value="{{$value->id}}"/><td></td>
<td><p data-placement="top" data-toggle="tooltip" title="" data-original-title="Tolltip">{{$value->page_name}}</p></td>
<td> <a href="" class="pglst-lnk"> {{$value->page_url}</a</td>
<td>
Now here i want to add two more values in blade template like {{$value->coupon_count}} and {{$value->total sum}}
But these two values are in different tables
How i can get these two values from different tables while i am having same views and i have already define controller method:
Any help would be highly appreciated!!
class PageList extends Model
{
protected $table = 'page_master';
protected $appends = ['page_particulars','page_coupon'];
protected $fillable = ['business_id', 'page_url', 'page_name'];
public function getpageParticularsAttribute(){
}
public function getpageCouponAttribute(){
}
}
class PageCoupon extends Model
{
protected $table = 'page_coupon';
protected $fillable = ['page_id','code','is_ordered','user_limit'];
}
and 2nd model is:
class Sale extends Model
{
protected $table = 'page_particulars';
protected $fillable = ['user_id','product_asin','page_expiry_date','market_place','promo_title','regular_price','promo_price','company_logo','coupon_file','email_from','email_subject','facebook_link','twitter_link','website_link','email_body'];
}
You can either add a relation to the other table
In your Model add
public function particulars()
{
return $this->hasOne('App\Sale','page_id');
}
and use
$value->particulars->regular_price;
or you can use Eloquent append to add new values to the same model
In your Model add
protected $appends = ['coupon_count','total_sum']
and a function to get the attribute
public function getCouponCountAttribute(){
//fetch from other table and return here for example
return Coupon::where('page_id',$this->id)->count();
}
public function getTotalSumAttribute(){
//fetch from other table and return here
}
I have a list of books and a list of authors. I made the Model relations, so that my Book Model says, that books->belongTo('Author') and my Author Model says, that authors->hasMany('Book').
So normally I could access the a variable through this:
$books = Book::all();
And then in the view:
#foreach($books as $book)
<div>{{$book->id}}</div>
<div>{{$book->title}}</div>
<div>{{$book->authors->firstname}}</div>
#endforeach
But this does not work. I get the error message: Trying to get property of non-object
So here are my files:
My Models:
Book.php
class Book extends \Eloquent {
protected $guarded = [];
public function religions()
{
return $this->belongsTo('Religion');
}
public function branches()
{
return $this->belongsTo('Branch');
}
public function authors()
{
return $this->belongsTo('Author');
}
public function quotes()
{
return $this->hasMany('Quote');
}
public function chapters()
{
return $this->hasMany('Chapter');
}
}
Author.php
class Author extends \Eloquent {
protected $guarded = [];
public function books()
{
return $this->hasMany('Book');
}
public function quotes()
{
return $this->hasMany('Quote');
}
public function branches()
{
return $this->belongsTo('Branch');
}
public function religions()
{
return $this->belongsTo('Religion');
}
}
Then come my controller:
ReligionBranchBookController
class ReligionBranchBookController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index($religionId, $branchId)
{
//
// $books = Book::where('religion_id', $religionId)->where('branch_id', $branchId)->get();
$books = Book::all();
$authors = Author::all();
// dd($books->toArray());
return View::make('books.index')
->with('religionId', $religionId)
->with('branchId', $branchId)
->with('books', $books)
->with('authors', $authors);
}
}
My Views:
index.blade.php
#extends('layout.main')
#section('content')
<h1>Books List!!</h1>
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
</tr>
#foreach($books as $book)
<tr>
<td>{{$book->id}}</td>
<td>{{$book->title}}</td>
<td>{{$book->authors->firstname}}</td>
</tr>
#endforeach
</table>
#stop
I know that it should normally work, I rebuild it with only books and authors, and it works fine there.
So, does anyone have an idea, where I am going wrong?
Thanks,
George
In your Book model change the authors method to author like this:
public function author()
{
return $this->belongsTo('Author');
}
Because, one book belongs to one author according to your relationship and when you call authors the belongsTo->getResults() get called and runs the wrong query so authors get null and you get the error. Things to remember:
For hasOne and belongsTo relationship use singular form of relationship method, i.e, author not authors.
hasOne or belongsTo returns a single model object.
For hasMany and belongsToMany relationship use plural form of relationship method, i.e, authors not author.
hasMany and belongsToMany returns a collection of model objects.
I am using laravel, I have a main table with 'projects' and a table with 'users', an intermediate table linking the two as a many-to-many relationship.
Now I want to display a list of projects, but if they are over 'projects.max_people' then they should be hidden from this list, how do I do this in laravel?
The problem is im 'get()'ing the users in the view, after I did Project::get()... how do I add this where condition?
You should create a new object called ProjectUser or so. In this object should contain a 'project_id' and 'user_id'.
Then, your Project model would look something like this:
<?php
class Project extends \Eloquent
{
protected $table = 'projects';
public function projectUsers(){
$this->hasMany('ProjectUser', 'project_id');
}
}
The User class:
<?php
class Project extends \Eloquent
{
protected $table = 'projects';
public function projectUsers(){
$this->hasMany('ProjectUser', 'user_id');
}
}
The ProjectUser class:
class ProjectUser extends \Eloquent
{
protected $table = 'project_users';
public function project(){
$this->belongsTo('Project'`enter code here`, 'project_id');
}
public function user(){
$this->belongsTo('User', 'user_id');
}
}
Now, you can get the users of a project like so:
$projects = Project::with('projectUsers.user')->get();
When looping through these objects you can access the user like this:
#foreach($projects as $project)
#foreach($project->projectUsers as $projectUser)
{{ $projectUser->user->id }}
#endforeach
#endforeach