How I use relationship in blade template (hasOne) || Laravel - php

Okay i'm trying get "likes" and "users" in Posts by relationship hasOne.
here is my Post.php Model
class Posts extends Model
{
protected $table = 'posts';
public function User()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function Like()
{
return $this->hasOne(Like::class, 'post_id', 'id');
}}
My Blade template
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{$deal->like->status}}
<br>
{{$deal->user->email}}
<div class="sl-item">
<div class="sl-left"> <img src=" {{asset( '/assets/images/users/2.jpg')}}" alt="user" class="img-circle"> </div>
<div class="sl-right">
<div> {{$deal->user->username}} || {{$deal->subject}} <Br> <span class="sl-date">{{$deal->created_at}}</span>
<div class="m-t-20 row">
<div class="col-md-3 col-xs-12"><img src="{{$deal->image}}" alt="user" class="img-responsive radius"></div>
<div class="col-md-9 col-xs-12">
<p> {{$deal->body}} </p> עבור למוצר </div>
</div>
<div class="like-comm m-t-20"> 2 תגובות <i class="fa fa-heart text-danger"></i> 5 לייקים </div>
</div>
</div>
</div>
</div>
<hr></div>
</div>
#endforeach
And there is my Controller
class PostsController extends Controller
{
public function showdeals()
{
$showdeals = Posts::with( 'User', 'Like')->get();
return view('posts.show', compact('showdeals'));
}
public function helpnewview(){
return view('posts.anew');
}
public function helpnew(Request $request){
//User pick link
$userlink = $request['userlink'];
return \Redirect::route('newdeal', compact('userlink'));
}
public function new(Request $request)
{
//Emdeb user link
$link = Embed::create($request['userlink']);
$linke = $request['userlink'];
return view('posts.new', compact('link', 'userlink', 'linke'));
}
public function create(Request $request)
{
$posts = New Posts;
$posts->user_id = Auth::User()->id;
$posts->subject = $request['subject'];
$posts->body = $request['body'];
$posts->link = $request['link'];
$posts->price = $request['price'];
$posts->image = $request['image'];
$posts->tag = $request['tag'];
$posts->save();
return back();
}
}
Now if I do something like {{$deal->user->email}} its will work,
if I go to something like this {{$deal->like->status}} its does not work,
am I missing something ?

If you want multiple relationships to be eagerly loaded you need to use an array of relationships: Model::with(['rl1', 'rl2'])->get();
public function showdeals()
{
...
$showdeals = Posts::with(['User', 'Like'])->get();
...
}
EDIT:
From that json in the comments that I see, there is no attribute named status in your Like model so thats probably the root of the problem

Controller edit this code
public function showdeals()
{
$showdeals = Posts::all();
return view('posts.show', compact('showdeals'));
}
And blade file code
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{ $deal->Like->status }}
<br>
{{ $deal->User->email }}
#endforeach

I think everything is good except
{{$deal->like->status}} {{$deal->user->email}}
Please try as
{{$deal->Like()->status}}
<br>
{{$deal->User()->email}}

Related

How to show summary data in Laravel Blade inside of ForEach Loop?

I am trying to display a ForEach loop on my view that shows each code type. That part works. I am having trouble figuring out how to display a count of how many pieces of code (stored in another table) exist for each code type. I don't understand how to use the id of the code_type to query the code_type_selected table and to return that count.
In my CodeType model
protected $fillable = [
'name',
'color',
'icon'
];
public function codeTypesSelected() {
return $this->hasMany(CodeTypesSelected::class, 'code_type_id', 'id');
}
In my CodeTypeSelected model
protected $fillable = [
'code_type_id',
'code_id',
];
public function codeTypes() {
return $this->belongsTo(CodeType::class, 'id', 'code_type_id');
}
In my controller
public function index(Request $request)
{
$codeTypes = CodeType::latest()->get();
$codeTypesSelected = CodeTypesSelected::latest()->get()->groupBy('code_type_id');
//dd($codeTypesSelected);
return view('code_layout.index', compact('codeTypes', 'codeTypesSelected'));
}
And in my view
<!-- /. ROW -->
<div class="row">
#foreach($codeTypes as $codeTypeItem)
<div class="col-md-3 col-sm-12 col-xs-12">
<div class="panel panel-primary text-center no-boder bg-color-{{ $codeTypeItem->color }}">
<div class="panel-left pull-left {{ $codeTypeItem->color }}">
<i class="fa fa-{{ $codeTypeItem->icon }} fa-5x"></i>
</div>
<div class="panel-right">
<h3>
{{ count($codeTypesSelected) }}
</h3>
<strong> {{ $codeTypeItem->name }} </strong>
</div>
</div>
</div>
#endforeach
</div>
<!-- /. ROW -->
Have you tried this
CodeType::latest()->withCount('codeTypesSelected')->get()

Missing required parameters for [Route: voluntier.submit.get] [URI: voluntier/submit/{id}]

I am currently working on my final project, but I got this error and I have tried to change the route action on my html to {{ route('voluntier.submit.get') }} but it still shows the error. Could anyone help me to find the solution.
Thank you so much
VoluntierController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Event;
use App\City;
use App\User;
use App\VoluntierProfile;
use App\Submission;
class VoluntierController extends Controller
{
public function index()
{
$data = Event::select('events.job_desk', 'events.location', 'events.city', 'events.job_description', 'events.fee', 'cities.name as city', 'job_desks.job_desk')
->leftJoin('job_desks', 'events.job_desk', 'job_desks.id')
->leftJoin('cities', 'events.city', 'cities.id')
->get();
$data_category_liaison = Event::select('events.job_desk')
->where('id' , '=', 2)
->count();
// dd($data_category);
return view('voluntier.index', compact('data', 'data_category_liaison'));
}
public function profile()
{
return view('voluntier.profile');
}
public function createProfile()
{
$city = City::all()->where('id', '!=', '0');
return view('voluntier.profile-edit', compact('city'));
}
public function storeProfile(Request $request)
{
$profile = new VoluntierProfile();
$profile->voluntier_id = $request->input('voluntier_id');
$profile->about = $request->input('tentang');
$profile->city_id = $request->input('kota');
$profile->address = $request->input('alamat');
$profile->latest_education = $request->input('pendidikan_terakhir');
$profile->save();
}
public function submitCreate($id)
{
$event = Event::find($id)->first();
$voluntier = Voluntier::find(Auth::user()->id)->get();
// dd($voluntier);
return view('voluntier.submit', compact('data'));
}
public function submitStore($id, Request $request)
{
$event = Event::find($id);
$voluntier = Auth::user();
$submission = new Submission();
$submission->event_id = $event->id;
$submission->voluntier_id = $voluntier->id;
$submission->status_id = $request->input('status');
$submission->save();
return redirect('voluntier/dashboard');
}
}
index.blade.php
#foreach($data as $row)
<td><a href="{{ route('voluntier.submit.get', $row->id) }}" class="job-item d-block d-md-flex align-items-center border-bottom fulltime">
<div class="company-logo blank-logo text-center text-md-left pl-3">
<img src="images/company_logo_blank.png" alt="Image" class="img-fluid mx-auto">
</div>
<div class="job-details h-100">
<div class="p-3 align-self-center">
<h3>{{ $row->job_desk }}</h3>
<div class="d-block d-lg-flex">
<div class="mr-3"><span class="icon-suitcase mr-1"></span>{{ $row->location }}</div>
<div class="mr-3"><span class="icon-room mr-1"></span>{{ $row->city }}</div>
<div><span class="icon-money mr-1"></span>Rp. {{ $row->fee }}</div>
</div>
</div>
</div>
<!-- <div class="job-category align-self-center">
<div class="p-3">
<span class="text-info p-2 rounded border border-info">Full Time</span>
</div>
</div> -->
</a></td>
#endforeach
submit.blade.php
<form action="{{ route('voluntier.submit.post', $event->id) }}" method="post" class="p-5 bg-white">
My route
web.php
Route::prefix('voluntier')->group(function() {
Route::get('/login', 'Auth\LoginController#showVoluntierLoginForm')->name('voluntier.login.get');
Route::post('/login/post', 'Auth\LoginController#voluntierLogin')->name('voluntier.login.post');
Route::get('/register', 'Auth\RegisterController#showVoluntierRegisterForm')->name('voluntier.register.get');
Route::post('/register/post', 'Auth\RegisterController#createVoluntier')->name('voluntier.register.post');
Route::get('/dashboard', 'VoluntierController#index')->middleware('auth:voluntier')->name('voluntier.dashboard');
Route::get('/profile', 'VoluntierController#profile')->middleware('auth:voluntier')->name('voluntier.get');
Route::get('/profile/get', 'VoluntierController#createProfile')->middleware('auth:voluntier')->name('voluntier.profile.get');
Route::post('/profile/post', 'VoluntierController#storeProfile')->name('voluntier.profile.post');
Route::get('/submit/{id}', 'VoluntierController#submitCreate')->middleware('auth:voluntier')->name('voluntier.submit.get');
Route::post('submit/post/{id}', 'VoluntierController#submitStore')->name('voluntier.submit.post');
});

Variable doesn't seem to be passing from controller to to view

I'm trying to pass a variable from a controller route to a view so i can display data relating to new assoicate model. It's working for other contrllers, but i can't figure out why it's not here.
Controller
#Index - Not passing down
public function index(){
$Advert = new PropertyAdvert();
return view('pages/Advert/index', compact('Advert'));
}
#Show - Is working, this is just an example.
public function show($id){
$user = Auth::user();
$Advert = PropertyAdvert::where('id', $id)->first();
return view('pages/Advert/show', compact('Advert', 'user'));
}
This is the route
Route::get('/property', 'AdvertisementController#index');
Route::get('/advertise', 'AdvertisementController#create')->middleware('auth');
Route::post('/createadvert', 'AdvertisementController#store');
Route::get('/property/{id}', 'AdvertisementController#show');
This is the template i'm trying to pass down to show.blade.php
<div class="row text-center" style="display:flex; flex-wrap:wrap">
<div class="col-lg-12">
<h3>Our most recent properties</h3>
#foreach ($Advert as $property)
<div class="col-md-3 col-sm-6">
<div class="thumbnail">
<img src="data:image/gif;base64,{{ $property->photo }}">
<div class="caption">
<h4>{{$property->address .', '. $property->town .', '. $property->county}}</h4>
</div>
<p>
More Info!
</p>
</div>
</div>
#endforeach
</div>
</div>
</div>
Try this:
public function index(){
$Advert = PropertyAdvert::get();
return view('pages/Advert/index', compact('Advert'));
}
You need to actually access the data for that model.

Laravel - Getting all records not just the first and putting together?

I have tried asking this question to everyone but nobody can see why I am trying to do it or why its not working but I will try my best to explain it properly this time.
I have a simple government page on my website that shows 3 panels in bootstrap with Higher Government, Senior Ministers and Junior Ministers. Inside each of them panels it shows a list of accounts assigned to that government rank.
Here is my government.blade.php:
#include('frontend.header')
<div class="col-md-12" style="padding-bottom:24px;">
<ul class="nav navtab nav-tabs" id="myTab" style="border-bottom:none;border-radius:1px;">
<li style="padding-right:13px;" class="active"><a style="" data-target="#higher_government_team" data-toggle="tab"><i class="fa fa-diamond" aria-hidden="true"></i> The Monarch/PM</a></li>
<li style="padding-right:13px;"><a style="" data-target="#senior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Seniors</a></li>
<li style="padding-right:13px;"><a style="" data-target="#junior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Juniors</a></li>
</ul>
</div>
<div class="col-md-8">
<div class="tab-content">
<div class="tab-pane active" id="higher_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
higher gov here
</div>
</div>
</div>
<div class="tab-pane" id="senior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
senior gov here
</div>
</div>
</div>
<div class="tab-pane" id="junior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
#foreach ($juniorGovernment as $governmentMember)
{{ $governmentMember->user_id }}<br>
#endforeach
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
#include('frontend.footer')
Here is my controller for displaying the page:
<?php
namespace App\Http\Controllers\Frontend\User;
use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;
class GovernmentController
{
public function getView()
{
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
$seniorGovernment = Cache::remember('government.senior_government', 1, function() {
return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
});
$juniorGovernment = Cache::remember('government.junior_government', 1, function() {
return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
});
return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
}
}
Now as you can see, I only select the first record where government_type matches. But the issue is I have multiple government roles with that government type and I want to get all the account stats for all records with that government type. I have looked at others suggestions and none of them work, either throwing an error or don't do what I want to do.
Now, I have modals for each Roleplay and GovernmentRoles, I have posted them both below.
GovernmentRole:
namespace App\Database\Website\Roleplay;
use Eloquent;
class GovernmentRole extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_government_roles';
public $timestamps = false;
protected $fillable = [];
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
}
Roleplay:
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovernmentRole', 'government_id');
}
}
So what I am trying to achieve is not just grabbing all the Roleplay instances for the FIRST government role record in the database it finds but putting together ALL roleplay instances for ALL records that match government_type either higher_government, senior_ministers, or junior_ministers.
If I understand what you are asking, can you not do something like fetching the stats on your loop through in blade? For example (I removed the cache, its adding complexity to the question/answer without any benefit):
// controller
$higherGovernment = GovernmentRole::where('government_type', 'higher_government')->get();
// blade
#foreach($higherGovernment as $g)
{{ $g->id }}
{{ $g->name }}
#foreach($g->stats as $stat)
{{ $stat->id }}
{{ $stat->something }}
#endforeach
#endforeach

Laravel Route not working. Did not get The id

I have now working on a project called Hospital & Doctor Information. Here I have different Division in Bangladesh & in each division there are districts in which there are certain types of hospital according to their ownership. But when I get the value of different hospital from it shows me some error.It did not find the specific id.I Have asked the ques before. But it did not solve my problem. So I ask this again. My route file
Route::get('/district/{id}', array('as' =>'district' ,'uses' => 'UserController#district'));
Route::get('/district/hospital/{id}', array('as' =>'hospital' ,'uses' => 'UserController#hospital'));
Route::get('/district/hospital/hospital_info/{id}', array('as' =>'hospital_info' ,'uses' => 'UserController#hospital_info'));
My Hospital Info Blade file is
<?php $active="hospital"; ?>
#extends('layouts.dashboard')
#section('content')
<section id="blog" class="container">
<div class="center">
<h2>Hospital Information</h2>
<h3 class="lead">The government approved a renowned hospital and improved quality of service address , doctor , patient viewing time, bed , pathological tests in various subjects including costs and find the information here .<br> The bed and cabin bookings online , pathological tests , the doctor can be a serial for the meeting from the app .</h3>
</div>
<div class="blog">
<div class="row">
<div class="col-md-12">
<div class="blog-item">
<div class="row">
<div class="col-xs-12 col-sm-4 blog-content">
<img class="img-responsive img-blog" src="images/2.jpg" width="100%" alt="" />
</div>
#foreach($division->districts as $district)
#foreach($district->cats as $category)
#foreach($category->hospitals as $hospital)
<div class="col-xs-12 col-sm-6 blog-content">
<h2>{{ $hospital->name }}</h2>
</div>
#endforeach
#endforeach
#endforeach
<div class="col-xs-12 col-sm-2 blog-content">
<h2>Share</h2>
<ul class="social-share">
<li><i class="fa fa-google-plus"></i></li>
<li><i class="fa fa-facebook"></i></li>
<li><i class="fa fa-twitter"></i></li>
<li><i class="fa fa-skype"></i></li>
</ul>
<br><br>
<a class="btn btn-success readmore" href="#">Booking</a>
</div>
</div>
</div><!--/.blog-item-->\
</div><!--/.col-md-8-->
</div><!--/.row-->
</div>
</section><!--/#blog-->
#stop
My Controller Is
public function district($id)
{
$divisions = Division::all();
$division=Division::find($id);
$district=District::find($id);
// $districts=District::where('division_id', '=', $divisions->id)->get();
if (!$division)
{
throw new NotFoundHttpException;
}
return view('users.district')
->with('divisions', $divisions)
->with('division', $division)
->with('district', $district);
}
public function hospital($id)
{
$divisions = Division::all();
$division=Division::find($id);
$district=District::find($id);
$categories=Category::all();
// $districts=District::where('division_id', '=', $divisions->id)->get();
// if (!$district)
// {
// throw new NotFoundHttpException;
// }
return view('users.hospital')
->with('divisions', $divisions)
->with('division', $division)
->with('district', $district)
->with('categories',$categories);
}
public function hospital_info($id)
{
$divisions = Division::all();
$division=Division::find($id);
$district=District::find($id);
$categories=Category::all();
$cats=Category::find($id);
$hospitals=Hospital::find($id);
// $districts=District::where('division_id', '=', $divisions->id)->get();
// if (!$district)
// {
// throw new NotFoundHttpException;
// }
return view('users.hospital_info')
->with('divisions', $divisions)
->with('division', $division)
->with('district', $district)
->with('categories',$categories)
->with('cats',$cats)
->with('hospitals',$hospitals);
}
The Model Hospital iS
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Hospital extends Model
{
protected $fillable = [
'name',
'division_id',
'district_id',
'category_id',
];
public function district()
{
return $this->belongsto('App\District');
}
}
The District Model Is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class District extends Model
{
protected $fillable=[
'name',
'division_id',
];
public function division()
{
return $this->belongsTo('App\Division');
}
public function category()
{
return $this->hasmany('App\Categories');
}
public function dcategory()
{
return $this->hasmany('App\Dcategories');
}
public function hospital()
{
return $this->hasmany('App\Hospital');
}
}
The Division model is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Input;
class Division extends Model
{
protected $fillable = ['name'];
public function districts()
{
// $divisions = Division::all();
// $division_id = Input::get('id');
return $this->hasMany('App\District','division_id');
}
}
The error is
I have asked the question a few days earlier but did not find the answer. Plz help me.
Your main problem is you're trying to get a hospital from id but you havn't defined any id in Hospital model so first thing first you should add id column to your Hospital model.
Secondly change your function from this
public function hospital_info($id)
{
$divisions = Division::all();
$division=Division::find($id);
$district=District::find($id);
$categories=Category::all();
$cats=Category::find($id);
$hospitals=Hospital::find($id);
// $districts=District::where('division_id', '=', $divisions->id)->get();
// if (!$district)
// {
// throw new NotFoundHttpException;
// }
return view('users.hospital_info')
->with('divisions', $divisions)
->with('division', $division)
->with('district', $district)
->with('categories',$categories)
->with('cats',$cats)
->with('hospitals',$hospitals);
}
To this
public function hospital_info($id)
{
$hospital=Hospital::find($id);
$divisions = Division::all();
$categories=Category::all();
// $districts=District::where('division_id', '=', $divisions->id)->get();
// if (!$district)
// {
// throw new NotFoundHttpException;
// }
return view('users.hospital_info') , compact('divisions','categories', 'hospital');
}
then you can get your infromation like this
<div class="col-xs-12 col-sm-6 blog-content">
<h2>{{ $hospital->name }}</h2>
</div>
#foreach($divisions as $itemDivision)
#foreach($categories as $itemCategory)
<div class="col-xs-12 col-sm-6 blog-content">
<h2>{{ $itemDivision->name }}</h2>
</div>
#endforeach
#endforeach
To get all the information about a District for example :
You should add the (id) column to all your models for using them later
inside your function do this :
public function district($id)
{
$district=District::findorfail($id);
$hospitals = DB::table('hospitals')
->leftjoin('districts' ,'hospitals.district_id' , '=', 'districts.id')
->where('district.id','=',$id)
->select('hospitals.*')
->get();
return view('users.district'),compact('district','hospitals') ;
}
Of course the hosptials is an array of objects and you should use a loop to get each hospital's informtaion

Categories