cant get data from show controller to view laravel 5.6 - laravel-5

my PostCOntroller
class PostController extends Controller
{
public function index()
{
$posts = post::all();
return view('posts.index',['p'=>$posts]);
}
public function show(post $post)
{
return view('posts.show', ['post'=>$post]);
}
master.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href = "/css/bootstrap.css">
<title>Document</title>
</head>
<body>
<div class="big-info p-5">
Home
Create
</div>
<div class="container">
<center><h1>POST<h1></center>
#yield('body')
</div>
index.blade.php
#extends('posts.master')
#section('body')
#foreach($p as $post)
<div class="card mt-2">
{{$post->title}}
</div>
#endforeach
#endsection
show.blade.php
#extends('posts.master')
#section('body')
<div class="card">
<div class="card-body">
<h3>{{$post->title}}</h3>
</div>
<div class="card-body">
<h3>{{$post->content}}</h3>
</div>
</div>
#endsection
web.php
Route::resource('hello','PostController');
php artisan route:list
GET|HEAD | hello | hello.index | App\Http\Controllers\PostController#index | web |
POST | hello | hello.store App\Http\Controllers\PostController#store | web |
GET|HEAD | hello/create | hello.create | App\Http\Controllers\PostController#create | web |
GET|HEAD | hello/{hello} | hello.show | App\Http\Controllers\PostController#show | web
i think i wrote everything right .. the index page is sending the id of the data from database... the controller is receiving the data in array $post and the show blade should show the data $post->title or $post->content but this is not happening
i think its a silly mistake but cant figure it out what
the problem is my show page is not showing data
please help
#
adding {{dd($post)}} in index page
post {#199 ▼
#fillable: array:2 [▼
0 => "title"
1 => "content"
]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▶]
#original: array:5 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▼
0 => "*"
]
}
adding {{dd($post)}} in show blade
post {#195 ▼
#fillable: array:2 [▶]
#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: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}

If $hello is the id of a post, your show controller should be:
public function show($hello)
{
$post = Post::find($hello);
return view('posts.show', ['post'=>$post]);
}

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);

I have a collection of objects in laravel. When I try to access it in blade it shows "Attempt to read property "year_month" on array"

^ Illuminate\Support\Collection {#1471 ▼
#items: array:9 [▼
0 => {#1490 ▼
+"year_month": "2022-01"
}
1 => {#1452 ▼
+"year_month": "2022-02"
}
2 => {#526 ▼
+"year_month": "2022-03"
}
3 => {#1453 ▼
+"year_month": "2022-04"
}
4 => {#1457 ▼
+"year_month": "2022-05"
}
5 => {#1458 ▼
+"year_month": "2022-06"
}
6 => {#1461 ▼
+"year_month": "2022-07"
}
7 => {#1463 ▼
+"year_month": "2022-08"
}
8 => {#1460 ▼
+"year_month": "2022-09"
}
]
#escapeWhenCastingToString: false
}
This is my collection. And I try to access it in Blade as
#if(!empty($monthYears))
<div class="pt-2 pb-2 carousel">
#foreach($monthYears as $monthYear)
<div wire:click="changePeriod('{{$monthYear->year_month}}')" class="text-gray-700 text-base mx-4 cursor-pointer carousel-cell #if($loop->index == count($monthYears)-2) is-clicked #endif">
{{date("m/y", strtotime($monthYear->year_month))}}
</div>
#endforeach
</div>
#endif
On the first load it loads without any issue. But when I click on any events of livewire components it shows "Attempt to read property "year_month" on array".
Here's my livewire component
public Collection $monthYears;
public function mount()
{
$this->monthYears = DB::table('table_name')->orderBy('year_month', 'asc')->groupBy('year_month')->get('year_month');
}
Livewire does not hydrate stdClass properties. They will be converted to array structure.
Note the supported types.

This collection can't be displayed on the blade

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.

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 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