Undefined property: stdClass:: in laravel - laravel

I want to show user orders and use this code:
#foreach($orderHistory as $order)
<div class="with-spacing three-col orders" id="works-grid">
<div class="work-item branding ui-ux">
<div class="work-detail">
<a href="#">
<img src="images/portfolio-1.jpg" alt="">
<div class="work-info">
<div class="centrize">
<div class="v-center">
<h3>{{ $order->product_name }}</h3>
<p> {{ $order->product_price }}</p>
</div>
</div>
</div>
</a>
</div>
</div>
</div>
#endforeach
controller:
$orderHistory = DB::table('cart')
->where('user_id', auth()->id())
->join('singleproducts', 'singleproducts.id', '=', 'cart.product_id')
->select('singleproducts.name', 'cart.qty', 'cart.product_price')
->get();
return view('UI.UserProfile.profile' , compact('orderHistory'));
and the error is: " Undefined property: stdClass::$product_name "
what is the problem?

Typo, you are selecting the column "name" from the database.
#foreach($orderHistory as $order)
<div class="with-spacing three-col orders" id="works-grid">
<div class="work-item branding ui-ux">
<div class="work-detail">
<a href="#">
<img src="images/portfolio-1.jpg" alt="">
<div class="work-info">
<div class="centrize">
<div class="v-center">
<h3>{{ $order->name }}</h3>
<p> {{ $order->product_price }}</p>
</div>
</div>
</div>
</a>
</div>
</div>
</div>
#endforeach
or change the query
$orderHistory = DB::table('cart')
->where('user_id', auth()->id())
->join('singleproducts', 'singleproducts.id', '=', 'cart.product_id')
->select('singleproducts.name as product_name', 'cart.qty', 'cart.product_price')
->get();
return view('UI.UserProfile.profile' , compact('orderHistory'));

The problem is that $orderis not an object and you're trying to access it like an object. Perhaps it's an array - try accessing it as such.
We can't be sure unless we see where $order is defined in your controller maybe. One quick way is to place a #dd($order) just after initializing the for loop. That dumps the variable so you can see it's format.
Your query should be like this:
$orderHistory = DB::table('cart')
->where('user_id', auth()->id())
->join('singleproducts', 'singleproducts.id', '=', 'cart.product_id')
->select('singleproducts.name as product_name', 'cart.qty as quantity', 'cart.product_price as product_price')
->get();
return view('UI.UserProfile.profile' , compact('orderHistory'));
So you end up with an array of objects in this format:
[
{
product_name: 'name',
product_price: 555.00,
quantity: 2
}
...
{}
]

Related

How do I do pagination on my code in Laravel?

So my front-end Lists of Businesses are not in paginated style. But I do not know how to do it. Can anyone please help? The code I posted is in my BusinessListController.php
BusinessListController.php
`<?php
namespace App\Http\Controllers;
use App\Models\Business;
use App\Models\Category;
use App\Models\Location;
use Illuminate\Http\Request;
class BusinessListController extends Controller
{
public function index(Request $request)
{
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->get();d
return view('pages.business-list', [
'businesses' => $businesses,
'locations' => Location::all(),
'categories' => Category::all()
]);
}
}`
And then here is the code for my view blade front-end
Business-List.blade.php
<div class="row business-list-row mx-auto">
#foreach ($businesses as $business)
<div class="col-md-4">
<div class="card shadow border-light mb-3">
<img
src="https://cdn1.clickthecity.com/images/articles/content/5d6eba1f4795e0.58378778.jpg"
class="card-img-top" alt="...">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4 class="card-title h6" style="font-weight: bold;">
{{Str::limit($business->name, 20, $end='...')}}
</h4>
<div class="">
<p class="card-text">
{{ $business->location?->name }}
</p>
<p class="card-text" style="color: #32a852;">
{{ $business->category?->name}}
</p>
</div>
</div>
<div class="align-self-center">
<a href="{{ route('store', $business->id) }}" class="btn btn-info stretched-link">
Visit
</a>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
So you need to do three things.
In Controller:
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->paginate(15);
put the number of items you need on a single page. here I put 15.
Put this under the </div> of your list.
{{ $business->links() }}
Put this inside the App\Providers\AppServiceProvider boot method.
use Illuminate\Pagination\Paginator;
public function boot()
{
Paginator::useBootstrapFive(); // or
Paginator::useBootstrapFour();
}
This depends upon which version of Bootstrap you are using.
Still confused? Checkout Laravel Pagination Documentation
Just remove ->get();d and add paginate
example
ModelName()->paginate();

Else Statement returned Blank in Laravel

I want to implement a simple search on my Laravel Application
public function search()
{
$search = request()->query('search');
if ($search) {
$books = Book::where('name', 'LIKE', "%{$search}%")->simplepaginate(12);
}
else {
echo "<h2>Book Not Found, please try using another search term</h2>";
$books = Book::orderBy('created_at', 'desc')->simplepaginate(12);
}
return view('search')->with('books', $books);
}
But the else returned a blank screen when the search terms can't be found
UPDATE
Here is my view file
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-10 offset-md-1">
<div class="row">
#foreach($books as $book)
<div class="col-md-3">
<div class="home-catalog-image">
<a href="{{ route('book', $book->id) }}" target="_blank">
<!-- <img src="{{ $book->image }}" alt="trending image" /> -->
<img src="{{ $book->image_url }}" class="img-responsive" alt="{{$book->image_url}}">
</a>
</div>
<p class="author">{{ $book->author->name }}</p>
<h1 class="book-title">{{str_limit($book -> name, 20) }}</h1>
</div>
#endforeach
</div>
<p style="text-align:center;>"> {!! $books->render() !!} </p>
</div>
</div>
</div>
Check how to use the request() helper to get the input.
Also you can use when() method for conditional clauses instead if else.
public function search()
{
$search = request('search', null);
$books = Book::when($search, function ($query, $search) {
return $query->where('name', 'LIKE', "%{$search}%");
})
->orderBy('created_at', 'desc')
->simplePaginate(12);
return view('search')->with('books', $books);
}
Then in Blade you can use #forelse directive to loop the collection, or if it's empty, show the message.
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-10 offset-md-1">
<div class="row">
#forelse ($books as $book)
<div class="col-md-3">
<div class="home-catalog-image">
<a href="{{ route('book', $book->id) }}" target="_blank">
<!-- <img src="{{ $book->image }}" alt="trending image" /> -->
<img src="{{ $book->image_url }}" class="img-responsive" alt="{{$book->image_url}}">
</a>
</div>
<p class="author">{{ $book->author->name }}</p>
<h1 class="book-title">{{str_limit($book -> name, 20) }}</h1>
</div>
#empty
<h2>Book Not Found, please try using another search term</h2>
#endforelse
</div>
<p style="text-align:center;>"> {!! $books->render() !!} </p>
</div>
</div>
</div>
To solve my problem, I use forelse instead of foreach a
#forelse($books as $book)
<div class="col-md-3">
<div class="home-catalog-image">
<a href="{{ route('book', $book->id) }}" target="_blank">
<!-- <img src="{{ $book->image }}" alt="trending image" /> -->
<img src="{{ $book->image_url }}" class="img-responsive" alt="{{$book->image_url}}">
</a>
</div>
<p class="author">{{ $book->author->name }}</p>
<h1 class="book-title">{{str_limit($book -> name, 20) }}</h1>
</div>
#empty
<h2>Book Not Found, please try using another search term</h2>
#endforelse
In my controller, I used
public function search()
{
$search = request('search', null);
$books = Book::when($search, function ($query, $search) {
return $query->where('name', 'LIKE', "%{$search}%");
})
->orderBy('created_at', 'desc')
->simplePaginate(12);
return view('search')->with('books', $books);
}

Invalid argument supplied for foreach with laravel 5.4

I'm getting Invalid argument supplied for foreach() error in my view after publishing a post and the code i use for looping in my controller is this:
public function edit($id)
{
$post = Post::find($id);
$categories = Category::all();
$cats = array();
foreach ($categories as $category) {
$cats[$category->id] = $category->name;
}
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
return view('admin.posts.edit')->withPost($post)->withCategories($cats)->withTags($tags2);
}
this is the only part i handle loops in my postcontroller edit section. And I know the issue is from Tags loop because when I remove the tags code in my view other part will show up correctly.
Oh and this is the loop i use in my view:
#extends('layouts.app')
#section('content')
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">{{ $post->title }}</div>
<div class="panel-body">
<p><img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" class="img-responsive" /></p>
<p>{!! $post->body !!}</p>
</div>
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach
</div>
</div>
</div>
#endsection
#section('sidebar')
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-info"></i> Post Info</div>
<div class="panel-body">
<dl class="dl-horizontal">
<label>URL:</label>
<p>{{ url('blog/'.$post->slug) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Created On:</label>
<p>{{ date('M j, Y h:ia', strtotime($post->created_at)) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Last Update:</label>
<p>{{ date('M j, Y h:ia', strtotime($post->updated_at)) }}</p>
</dl>
<dl class="dl-horizontal">
<label>Posted In:</label>
<p>{{ $post->category->name }}</p>
</dl>
<hr/>
<div class="row">
<div class="col-md-6">
{!! Html::linkRoute('posts.edit', 'Edit', array($post->id), array('class' => 'btn btn-warning btn-block')) !!}
</div>
<div class="col-md-6">
{!! Form::open(['route' =>['posts.destroy', $post->id], 'method' => 'DELETE']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-block']) !!}
{!! Form::close() !!}
</div>
</div>
<hr/>
{!! Html::linkRoute('posts.index', '<< Back to Posts', [], array('class' => 'btn btn-primary btn-block')) !!}
</div>
</div>
</div>
#endsection
PS: I'm using Laravel 5.4
Post updated view!
You can't get tags via post so Try this...
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach
</div>
Try:
return view('admin.posts.edit')->with("post",$post)->with("categories",$cats)->with("tags",$tags2);
and at view
<div class="tags">
#foreach ($tags as $tag)
<span class="label label-default">{{ $tag->name }}</span>
#endforeach
</div>
in your table if your primary key name if not id you have to mention in your relationship Link
2.for your post has one category so you can show this into your view like this
{{ $post->category->name }}
if you get result you can use it. but seems you need tag key and value pair so use this methods
$tags = Tag::where('post_id',$post->id)->groupBy('id')->get();
or try your way
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
return view('admin.posts.edit',compact($post,$tags2,$cats));
in your view try this
#foreach ($tags as $key => $tag)
<span class="label label-default">{{ $tag }}</span>
#endforeach

using Pagination with orderBy Eloquent Model

I have a function witch is getting all properties joining the images tables with orderBy and need to add paginate
here is my function
public function show_all()
{
$properties = PropertyDetail::where('active', 1)->with('propImages')->paginate(15)
->orderBy('id', 'DESC')
->get();
return View::make('portal.properties.view_all', compact('properties'));
}
in my view I got
call_user_func_array() expects parameter 1 to be a valid callback,
class 'Illuminate\Support\Collection' does not have a method 'orderBy'
another thing when I removed the orderBy('id', 'DESC')->get() and I try
it works but when I try to put {{ $prop->links() }} in the view I got
Call to undefined method Illuminate\Database\Query\Builder::links()
here is how my view looks like
#foreach($properties as $prop)
<div class="property col-xs-12 col-sm-6 col-md-4">
<div class="image">
<div class="content imgContainer">
{{ HTML::link('property-details/'.$prop->id, '') }}
#foreach($prop->propImages->slice(0, 1) as $image)
{{ HTML::image('images/propertyImages/'.$image->image, $prop->title) }}
#endforeach
</div>
<div class="price"> OMR. <span class="priceNumber"> {{ $prop->price }}</span></div>
</div>
<div class="title">
<h2>{{ HTML::link('', $prop->title, array('title'=>'$prop->title')) }}</h2>
</div>
<div class="location">{{ trans('location.'.$prop->propLocation->city) }}</div>
<div class="bathrooms">
<div class="content">{{ $prop->bathroom }}</div>
</div>
<div class="bedrooms">
<div class="content">{{ $prop->bedroom }}</div>
</div><!-- /.bedrooms -->
<div class="receptionRoom">
<div class="content">{{ $prop->dining_room }}</div>
</div>
</div>
#endforeach
{{ $prop->links() }}
The correct syntax is:
$properties = PropertyDetail::where('active', 1)
->with('propImages')
->orderBy('id', 'desc')
->paginate(15);

Default pagination fails in Laravel

I am creating an basic pagination with Laravel5.1 , I receive the following PHP code.
public function postFindUsers(){
$name= \Request::input('name');
$findUserByNombre = User::where('name', 'LIKE', '%'.$name.'%')->paginate(6);
return view('users.findUsers')->with('users',$findUserByNombre);
}
This code returns the list of users correctly but in the view I don't know how to solve this error , I have the following code.
<div class="hotel-list listing-style3 hotel">
#foreach($users as $usuario)
<article class="box">
<figure class="col-sm-5 col-md-4">
<img width="270" height="160" alt="" src="{{$usuario->foto}}">
</figure>
<div class="details col-sm-7 col-md-8">
<a href="{{ URL::asset('detalle') }}">
<div>
<div>
<h4 class="box-title">{{$usuario->nombre}} {{$usuario->primer_apellido}} {{$usuario->segundo_apellido}}<small><i class="soap-icon-departure yellow-color"></i> {{$usuario->fecha_nacimiento}}</small></h4>
</div>
</div>
<div>
<p>{{$usuario->descripcion}}</p>
<div>
<a class="button btn-small full-width text-center" title="" href="detalle">CONSULTAR</a>
</div>
</div>
</a>
</div>
</article>
#endforeach
{{$users->render()}}
</div>
However , when I put this url in the page public/search?page=2 , this url return a typical error MethodNotAllowedHttpException in RouteCollection.php line 219:
Could anyone help to me ?
/UPDATE/
Route::get('/search-users', 'UserController#getUsers');
Route::post('/search', 'UserController#postFindUsers');
Get request
routes
Route::get('/search', 'UserController#getFindUsers');
controller
public function getFindUsers(){
$name= \Request::input('name');
$findUserByNombre = User::where('name', 'LIKE', '%'.$name.'%')->paginate(6);
return view('users.findUsers')->with('users',$findUserByNombre);
}
HTML
{!! Form::input ('search' , 's' , null , ['class' => 'form-control'] , ['placeholder' => 'Search...']) !!}
You can return both $findUserByNombre and $links in the function postFindUsers()
public function postFindUsers(){
$name= \Request::input('name');
$findUserByNombre = User::where('name', 'LIKE', '%'.$name.'%')->paginate(6);
$links = $findUserByNombre->render();
return view('users.findUsers', compact('findUserByNombre', 'links'));
}
And in the view findUsers.blade.php, just add
<div>{!! $links !!}</div>
And change the request method from post to get.
Route::get('/search', 'UserController#postFindUsers');
To get the 2nd page, just call the following url
public/search?page=2

Resources