using Pagination with orderBy Eloquent Model - laravel

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

Related

How to get currencies from rest coutries API v3.1 using Laravel?

#foreach ($responseBody as $response)
<div class="row">
<div class="col-4">Official Name</div>
<div class="col-8">{{$response->name->official}}</div>
</div>
<div class="row">
<div class="col-4">Currencies</div>
<div class="col-8">{{ $response->currencies???? }}</div>
</div>
#endforeach
I using Laravel to consume API from https://restcountries.com/. I success to get Name of the country, but I still failed to get the currencies. The "SGD" code is different for each country.
How to get the name of currencies?
You should run another loop for the currencies:
#foreach($response->currencies as $id => $info)
<b>{{ $id }}</b>: {{ $info->name }} {{ $info->symbol }}
#endforeach

Undefined property: stdClass:: in 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
}
...
{}
]

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

Accessing collection from a relationship

So I have 2 tables.
DirtyEvent model and Event model.
I am retrieving DirtyEvent with Event which works fine
In blade I have:
#if (\Request::is('profile/event'))
#foreach ($events as $event)
#if (empty( $event->image ))
<div class="card-header">
<span class="card-title"> {{($event->title) }}</span>
</div>
#else
<div class="card-image">
<img class="img-responsive" src="{{ $event->image }}"></img>
<span class="card-title"> {{($event->title) }}</span>
</div>
#endif
<div class="card-content">
<p><strong>Starts: </strong>#php echo ($startdate) #endphp - {{$event->startime }}</p>
<br>
#if ($startdate != $enddate)
<p><strong>Ends: </strong>#php echo ($enddate) #endphp - {{$event->endtime }}</p>
<br>
#endif
<p><strong>Description:</strong></p>
<br>
<p>{{$event->description }}</p>
</div>
<div class="card-action">
<i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i>
<form method="POST" action={{ url('events/delete/' . $event->id) }}>
{{ method_field('PATCH') }}
{{ csrf_field() }}
<button type="submit" class="delete" style="border:none;"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></button>
</form>
</div>
#foreach ($events->publicevents as $eventss)
{{dd($events)}}
#endforeach
#endforeach
However dd($events) gives me:
DirtyEvent Collection -> relations -> publicevents -> Event collection
But, It is saying that publicevents do not exist in current collection.
Controller
public function index()
{
$id = Auth::id();
$events = DirtyEvent::where('user_id', $id)
->with('publicevents')
->get();
return view('events.viewEvent', compact('events'));
}
Model
public function publicevents()
{
return $this->hasMany('App\Event', 'event_id');
}
I guess not all dirty event objects have events. So check this first with empty() or isEmpty() or count():
#if (!empty($event->publicevents))
#foreach ($event->publicevents as $eventss)
{{ $eventss->id }}
#endforeach
#endif
Update
It should be $event->publicevents, not $events->publicevetns.

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

Resources