This collection can't be displayed on the blade - laravel

I have function to export PDF .
this is have more than 1 collection data on this 1 view . like this
public function PDF(Request $request,$id){
$users = User::findOrFail($id);
$pendidikan = Data_riwayat_pendidikan::where('user_id',$id)->get();
$pdf = PDF::loadView('admin.pdf',['users' => $users,'pendidikan'=>$pendidikan]);
return $pdf->stream('Profile.pdf')->header('Content-Type','application/pdf');
}
I can displayed USERS data , like this {{ $users->nama}}
it's show normally but . I try this {{ $pendidikan->jenjang}} it's have error:
Property [jenjang] does not exist on this collection instance. (View: C:\xampp\htdocs\project\resources\views\admin\pdf.blade.php)
I try dd($pendidikan); and show like this:
Collection {#340 ▼
#items: array:1 [▼
0 => Data_riwayat_pendidikan {#345 ▼
#table: "data_riwayat_pendidikan"
#guarded: []
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▼
"id" => 1
"user_id" => 14
"jenjang" => "PERGURUAN TINGGI"
"nama_tempat" => "Universitas blablabla"
"jurusan" => "Rekam Medis"
"lulus_tahun" => "2000"
"gelar" => "gelar"
"created_at" => "2019-07-31 08:52:30"
"updated_at" => "2019-07-31 08:52:30"
]
#original: array:9 [▶]
it's can showed at die dump . how can I fix it?

$users is a single object. so you can access its properties like that.
But $pendidikan is a collection. not a single object. so you have to loop through it.
Possible solution
if you are doing this on a blade file.
#foreach($pendidikan as $item)
{{ $item->jenjang }}
#endforeach

you can try this
#if(isset($pendidikan))
<script>
var dataJson = JSON.parse("{!!$pendidikan!!}");
</script>
#endif
or
{!!$ pendidikan-> jenjang!!}
laravel document
Displaying Unescaped Data
By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
Hello, {!! $name !!}.
Be very careful when echoing content that is supplied by users of your application. Always use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

Related

Laravel 9 Relationships Not Returning an Array of Data [duplicate]

This question already has answers here:
Property [title] does not exist on this collection instance
(8 answers)
Closed last month.
I am attempting to build a query that pulls from two tables with a one-to-many relationship. Rather than getting an array of data that exists for the relations, the output of the dd($customer); is:
0 => App\Models\Customer {#1496 ▼
#connection: "mysql"
#table: "customers"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:42 [▶]
#original: array:42 [▶]
#changes: []
#casts: array:1 [▶]
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"xray_machine" => Illuminate\Database\Eloquent\Collection {#1538 …2}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: array:34 [▶]
#guarded: array:1 [▶]
#forceDeleting: false
}
Customer Model
public function xray_machine()
{
return $this->hasMany(Xray_machine::class);
}
Xray_machine Model
public function customer()
{
return $this->belongsTo(Customer::class);
}
Controller
public function epes_scheduled(){
$customers = Customer::with('Xray_machine')->get();
dd($customers);
return view('work_orders/epe_scheduled', compact('customers'));
}
and in the view (by removing the dd() in controller I get this error:
Property [model] does not exist on this collection instance.
The View
#foreach ($customers as $customer)
<tr>
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="ml-4">
<div class="text-sm font-medium text-gray-900">
#if($customer->customer_name) {{$customer->customer_name}} #endif
</div>
</div>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="ml-4">
<div class="text-sm font-medium text-gray-900">
#if($customer->Xray_machine->model) {{$customer->Xray_machine->model}} #endif
</div>
</div>
</div>
</td>
</tr>
#endforeach
You are in right track and also the laravel is returning data perfectly. Laravel gives you the collection of the data instead of array. If you need array you can use toArray() method which gives you data in array.
$customers = Customer::with('Xray_machine')->get()->toArray();
dd($customers);

Laravel: Same Variable not working in different view

If i use the variable tests everything works:
My Controller:
public function index()
{
$row = Test::count();
$tests = Test::latest()->paginate($row);
return view('tests.index',compact('tests'));
}
public function show(Test $test)
{
return view('tests.show', compact('test'));
}
My Index-View:
#foreach($tests as $test)
<div class="event">
<h4 class="eventtitle text-j4y-dark">{{ $test->body }}</h4>
Mehr lesen »
</div>
#endforeach
My Show-View:
<h4 class="eventtitle text-j4y-dark">{{ $test->body }}</h4>
but if i use the variable event the index page wokrs so it shows me all of my events but if i click on one event for more details it shows me nothing and nothing works but i don't know why? its the same code only different variables ?
I don't know what to do
My Controller:
public function index()
{
$row = Event::count();
$events = Event::latest()->paginate($row);
return view('tests.index',compact('events'));
}
public function show(Event $event)
{
return view('tests.show', compact('event'));
}
My Index-View:
#foreach ($events as $event)
<div class="event">
<h4 class="eventtitle text-j4y-dark">{{ $event->eventtitel }}</h4>
<div class="date"><i class="far fa-calendar-alt"></i>{{ date("d.m.Y", strtotime($event->datum)) }}</div>
<p class="eventtext" id="eventtext">{{ $event->eventbeschreibung }}</p>
Mehr lesen »
</div>
#endforeach
My Show-View:
<div class="event">
<h4 class="eventtitle">{{ $event->eventtite l}}</h4>
<div class="date"><i class="far fa-calendar-alt"></i>{{ date("d.m.Y", strtotime($event->datum)) }}</div>
<p class="eventtext" id="eventtext">{{ $event->eventbeschreibung }}</p>
</div>
if i use dd($test) it shows me this:
Test {#692 ▼
#fillable: array:1 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:4 [▶]
#original: array:4 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
if i use dd($event) it shows me this:
Event {#660 ▼
#fillable: array:5 [▶]
+timestamps: false
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
if i use echo $event in my controller
it shows me this: []
if i use print_r($event)
it shows me this:
App\Event Object ( [fillable:protected] => Array ( [0] => firmenname [1] => eventtitel [2] => eventbeschreibung [3] => datum [4] => anhang ) [timestamps] => [connection:protected] => [table:protected] => [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => [wasRecentlyCreated] => [attributes:protected] => Array ( ) [original:protected] => Array ( ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) )
Well, there are lot of issue with you code. First thing is the pagination.
$row = Event::count(); //This is basically counting all the events you have
$events = Event::latest()->paginate($row); // And here u telling to pageinit with all events in single page.
I personally do not think it is the right way. If I had to do I would do this way
$events = Event::orderBy('created_at','desc')->get(); //This will allthe even in single page with the latest one.
If you only need all the events and sorting is not required I would do like this
$events = Event::all(); //This is give all the events
Coming back to your question.
A variable defined inside a controller method stays inside that method and the view that method is rendering. It does not pass another blade until and unless you are declaring it globally in the provider.
For your case, i would do something like this
Route
Route::get('events',['as'=>'events','uses'=>'ControllerName#index']);
Route::get('event/{id}',['as'=>'event.detail','uses'=>'ControllerName#show']);
Controller
public function index()
{
$data['events'] = Event::orderBy('created_at','desc')->get();
return view('tests.index',$data);
}
public function show($id)
{
$data['eventDetail'] = Event::where('id',$id)->first();
return view('tests.show',$data);
}
Index view
#foreach ($events as $event)
<div class="event">
<h4 class="eventtitle text-j4y-dark">{{ $event->eventtitel }}</h4>
<<CODE HERE MORE CODE >>
Mehr lesen »
</div>
#endforeach
Event detail view
<div class="event">
<h4 class="eventtitle">{{ $eventDetail->eventtite l}}</h4>
<div class="date"><i class="far fa-calendar-alt"></i>{{ date("d.m.Y", strtotime($eventDetail->datum)) }}</div>
<p class="eventtext" id="eventtext">{{ $eventDetail->eventbeschreibung }}</p>
</div>
Hope this helps

Laravel old() function not working --- flash dose not work (stoped working!!)

I'm trying to use old() in Laravel but it doesn't work.
In my controller:
dd(back()->withInput());
this is the session result
#session: Store {#364 ▼
#id: "dyNmtFJVQCQmcCob4SPYEBzWHJ6TJeM9X0mzWWu7"
#name: "laravel_session"
#attributes: array:6 [▼
"_token" => "NVJATvxuHRlGbAC1jUEIjS6gbLQQEWPIIV41fLYd"
"url" => []
"_previous" => array:1 [▼
"url" => "http://localhost:8000/units/23/rents/create"
]
"_flash" => array:2 [▼
"old" => []
"new" => array:1 [▼
0 => "_old_input"
]
]
"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 1
"_old_input" => array:5 [▼
"_token" => "NVJATvxuHRlGbAC1jUEIjS6gbLQQEWPIIV41fLYd"
"contract_id" => "20"
"unit_id" => "23"
"amount_paid" => "1"
"submit" => "submit"
]
]
#handler: FileSessionHandler {#363 ▶}
#started: true
value="{{ old('amount_paid')}}" I would get empty field
value="{{ old('amount_paid','test') }}" I would get 'test' in the field
I'm using Laravel 5.6
EDIT
to clarify the above code it to debug
this is my original code
controller
return back()->withInput();
view
<div class="form-group">
<label> amount paid </label>
<input type="float" class="form-control" name="amount_paid" value="{{ old('amount_paid')}}" required>
</div>
adding the method that handle the request
public function store(Request $request)
{
// updating the amount paid
$rent = new Rent;
$rent->amount_paid = $request->amount_paid;
try {
$rent->save();
} catch (\Illuminate\Database\QueryException $e) {
//return to the form and populate it
return back()->withInput();
}
return redirect('units/'.$request->unit_id);
** update **
It appear that session->flash is not working.
I tried a new installation of laravel and it is working fine
The problem was related to session it self.
I have 2
\Illuminate\Session\Middleware\StartSession::class,
one in middleware and another in $middlewareGroups[web].
this was a result of following a tutorial in youtube months ago to implement localisation :(

Get id of collection in foreach

I'm trying to get the ID of the share, but, I'm do a foreach in links, look:
#foreach($user->getRelation('shares')->pluck('links') as $link)
{{ $link->first()->title }} //works
{{ //get the ID, of the current share }}
#endforeach
How can I do it?
dd($user->shares);
Collection {#338 ▼
#items: array:3 [▼
0 => Share {#343 ▼
#attributes: array:6 [▼
"id" => 7
"link_id" => 3
"user_id" => 1
"shared_in" => null
"content" => "testetste"
"created_at" => "2018-02-02 15:46:13"
]
#relations: array:1 [▼
"links" => Collection {#349 ▶}
]
}
1 => Share {#344 ▶}
2 => Share {#345 ▶}
]
}
You can specify id as the second parameter for pluck() method:
#foreach($user->getRelation('shares')->pluck('links', 'id') as $id => $link)
{{ $link->first()->title }}
{{ $id }}
#endforeach
In this instance, your shares? are already shared with the view in their entirety and so plucking the links and ids doesn't really save you much performance meaning this loop is unnecessarily complicated.
#foreach($user->getRelation('shares') as $share)
{{ $share->links->first()->title }}
{{ $share->id }}
#endforeach
If however, all you want to use in this view instance is the link and id, then I would recommend modifying your query in the controller to reduce the size of the overall collection being sent to your view instance.

Laravel get products in the same category

Hi im trying to pass all the products in the same category to a view
my products table has cat_id which related to cat_id in the categories table,
i got all the data from a product id to a single product view and i want to show related products to that product too
here my passing to product page's controller
public function product($id){
$product = Products::where('pro_id',$id)->Paginate(1);
$products=Products::where('cat_id',$product->cat_id)->get();
return view('front.product.product', compact('product','products'));
}
the $product variable works
but not the $products variable
i get the following error when try to uses $products variable
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$cat_id
and my variables when trying to pass to view
#foreach($product as $show)
<div class="col-md-9">
<div class="col-md-5 grid">
<div class="thumb-image"> <img src="{!! url('public/backend/images/products/'.$show->pro_img) !!}" data-imagezoom="true" class="img-responsive" style="width: 305px; height: 400px;"> </div>
</div>
<div class="col-md-7 single-top-in">
<div class="single-para simpleCart_shelfItem">
<h1>{{$show->pro_title}}</h1>
<p>{{$show->pro_descript}}</p>
<label class="add-to item_price">{{$show->pro_price}}</label>
<div class="available">
<h6>Description</h6>
<h4>{{$show->pro_detail}}</h4>
</div>
Add to cart
</div>
</div>
<div class="clearfix"> </div>
<div class="content-top1">
<div class="clearfix"> </div>
</div>
#foreach($products as $related)
<div class="col-md-4 col-md3">
<div class="col-md1 simpleCart_shelfItem">
<a href="single.html">
<img class="img-responsive" src="{!! url('public/backend/images/products/'.$related->pro_img) !!}" alt="" />
</a>
<h3>{{$related->pro_detail}}</h3>
<div class="price">
<h5 class="item_price">{{$related->pro_price}}</h5>
Add To Cart
<div class="clearfix"> </div>
</div>
</div>
</div>
#endforeach
</div>
#endforeach
when i dd($product) with paginate(1)
LengthAwarePaginator {#237 ▼
#total: 1
#lastPage: 1
#items: Collection {#226 ▼
#items: array:1 [▼
0 => Products {#232 ▼
#table: "tbl_products"
#primaryKey: "pro_id"
+timestamp: false
#filltable: array:9 [▼
0 => "cat_id"
1 => "pro_title"
2 => "pro_descript"
3 => "pro_detail"
4 => "pro_img"
5 => "quantity"
6 => "pro_date"
7 => "pro_price"
8 => "pro_status"
]
#connection: "mysql"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:12 [▼
"pro_id" => 2
"cat_id" => 9
"pro_title" => "veston "
"pro_descript" => "look good"
"pro_detail" => "blue jean"
"pro_img" => "1516593265.jpg"
"quantity" => 8
"pro_date" => "2018-01-22 10:54:25"
"pro_price" => 400.0
"pro_status" => 0
"created_at" => "2018-01-22 03:54:25"
"updated_at" => "2018-01-22 03:54:25"
]
#original: array:12 [▼
"pro_id" => 2
"cat_id" => 9
"pro_title" => "veston "
"pro_descript" => "look good"
"pro_detail" => "blue jean"
"pro_img" => "1516593265.jpg"
"quantity" => 8
"pro_date" => "2018-01-22 10:54:25"
"pro_price" => 400.0
"pro_status" => 0
"created_at" => "2018-01-22 03:54:25"
"updated_at" => "2018-01-22 03:54:25"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▼
0 => "*"
]
}
]
}
#perPage: 1
#currentPage: 1
#path: "http://localhost:81/shop/product/2"
#query: []
#fragment: null
#pageName: "page"
}
$product = Products::where('pro_id',$id)->Paginate(1);
this code returns array
cahnge code to like below:
$product = Products::where('pro_id',$id)->first();
Here you are calling a paginator:
$product = Products::where('pro_id',$id)->Paginate(1);
Try this instead:
$product = Products::where('pro_id',$id)->first();
-or-
$product = Products::where('pro_id',$id)->paginate(1)[0];
-or finally-
$product = Product::findOrFail($id);
The latter would only work if you've set protected $primaryKey = 'pro_id'; within your class.
The details:
When you called $product = Products::where('pro_id',$id)->Paginate(1);' you are getting aPaginatorinstance back from the data layer. ThePaginatordoesn't have the properties that aProduct` does in your example, which is where the error is coming from.
A paginator is a different type of collection, but it is a type of collection, also. Think about it like an array or like a Java style ArrayList which is a complex wrapper class for an array that provides additional funcitonality. A paginator is similar, but with an extra level of abstraction to provide view based pagination. You can access objects on the 'page' within the paginator similarly to how you can get array-like access to objects in a collection.
If you just return a collection, then doing
$product = Products::where('pro_id',$id)->get();
Gives you the the matching id as a collection. In order to actually see the object you want you would need to do this:
$product = Products::where('pro_id',$id)->paginate(1)[0];
to get the first item in that collection.

Resources