Handling non objects - laravel

I might have a controller function like so
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
This is fine if the three collections I am obtaining contain data. If they dont and I try to visit the index page, I get
ErrorException in PollResponseController.php line 20: Trying to get property of non-object
So what is the best way to handle non-object's? To bypass this, I could do
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
if($poll) {
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
if($question) {
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
}
return view('error');
}
But is that not a bit exessive? I was just wondering if there was a better approach to handling this?
Thanks

You can use simple if($question) clause or if(is_null($question)).
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
if($question){
// The object is not empty, so I'll use it
}else{
// The object is empty
}
In a blade template it will look like #if($question) and #if(is_null($question)) respectively.
#if($question)
{{ $question->property }}
#endif
In most cases you should just bypass all variables in a template and then check each of them with #if clauses.

Related

I can't edit the ids in a map of a Laravel collection

Hello everyone I have this problem with the Models and Map in Laravel:
I have a code that is more or less like this:
public function getProducts()
{
$products = Product::selectRaw('
products.id,
products.name
');
return $products->paginate(15);
}
public function parseProducts()
{
$data = $this->getProducts();
$data->map(function ($item) {
$item->id = $this->encrypt($item->id);
return $item;
});
return $data;
}
The encryption code works fine but in this loop it doesn't, it returns all ids with 0.
If I use DB::table("products") instead of Product everything works fine.
Will there be any blockage?

Which design pattern helps me in this case using - Laravel

so I have a controller which returns a view with a DB Collection which I have a repository,
now, in case I have a request I want to return an array - json and not a view
any ideas if this is the correct approach?
public function index(
Request $request,
CampaignPerformanceRepository $campaignPerformanceRepository
) {
$data = $campaignPerformanceRepository->getDataByPeriod($request);
if ($request->all()) {
return $campaignPerformanceRepository->getDataByPeriod($request);
}
return view('reports.campaign-performances', compact('data'));
}
I do something similar in cases where I may want to return a view or just json based on the request. There's an easy helper function request()->wantsJson() which you can use.
$data = $campaignPerformanceRepository->getDataByPeriod($request);
if ($request->wantsJson()) {
return $campaignPerformanceRepository->getDataByPeriod($request);
}
return view('reports.campaign-performances', compact('data'));

Trying to get property 'post_titile' of non-object

This is My Controller.
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
//dd($page);
return view('web_views.index',['page' => $page]);
}
This is my view page
<h4>{{$page->post_titile}}</h4>
It's better to use Route-Model Binding I think.
Your route (if you are using resource route, it's already done):
Route::get('posts/{post}', 'PostController#show); // domain.tld/posts/1
Your method should look like this:
public function show(Post $post)
{
return view('web_views.index',compact('post'));
}
In your view:
<h4>{{ $post->post_titile }}</h4>
May be $posts->id you are passing, has no result in database so you need to check it by using if-statement
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
if($page == null){
$page = ['post_title' => 'Not Available'];
}
return view('web_views.index',['page' => $page]);
}
I believe this error is because of not finding data for an ID into database. So if as per above script will pass the fetched data to view otherwise it will push an item into $page array.

Input array loop on controller laravel 5

I have inputs array and i need to make a foreach but laravel $request->all() only return last one:
url:
http://localhost:8000/api/ofertas?filter_pais=1&filter_pais=2&filter_pais=3
controller:
public function filtroOfertas(Request $request){
return $request->all();
}
result:
{"filter_pais":"3"}
result should return 1, 2 and 3 and i need to make a foreach in filter_pais.
Any solution? Thanks
Use [] at the key of query string.
http://localhost:8000/api/ofertas?filter_pais[]=1&filter_pais[]=2&filter_pais[]=3
It will be parsed as array.
Repeated parameters make no sense and should be avoided without exception.
But looking at other solutions, there are several:
routes.php
Route::get('/api/ofertas/{r}', 'Controller#index');
Controller:
public function index($r)
{
$query = explode('&', $r);
$params = array();
foreach($query as $param)
{
list($name, $value) = explode('=', $param);
$params[urldecode($name)][] = urldecode($value);
}
// $params contains all parameters
}
Given that the URL has no question marks:
http://localhost:8000/api/ofertas/filter_pais=1&filter_pais=2&filter_pais=3

codeigniter passing count_all_results to view

I'm using the count_all_results() function to return a user's number of languages spoken. But when I try to pass the number to the view, I keep getting a php undefined variable (for $lang_cnt). Below is my code:
Model
function countLanguages($id) {
$this->db->where('user_id', $id)->from('languages');
return $this->db->count_all_results();
}
Controller
function showLangCount() {
$data['lang_cnt'] = $this->language_model->countLanguages($id);
$this->load->view('lang_view', $data);
}
View
<p>This user speaks <?php echo $lang_cnt; ?> languages.</p>
One problem is that your model function takes two arguments:
function countLanguages($id, $cnt_languages)
But when you call it you are only passing one argument:
$this->language_model->countLanguages($cnt_languages);
And an even bigger problem, as Rocket points out, is that countLanguages doesn't return anything. Try this:
function countLanguages($id) {
$this->db->where('user_id', $id)->from('languages');
return $this->db->count_all_results();
}
Always check your model functions if they return value or not. Try this:
function showLangCount() {
if($this->language_model->countLanguages($id))
{
$data['lang_cnt'] = $this->language_model->countLanguages($id);
}
else
{
$data['lang_cnt'] = NULL;
}
$this->load->view('lang_view', $data);
}
Its better to use:
return $query->num_rows();
to return the number of rows effected...

Resources