I'm doing a blog to learn how to use laravel. The blog is mostly finished but I still found some mistakes in my code. Most of them are solved but there is still one error I can't fix.
It's about the 'my thread' of the user. If the user did a new account, he also get a 'my thread' page. If he's klicking on the page, he will get a view with all his threads. My problem now is, that if he don't have any threads, he will get a:
trying to get property of non-object exception. Of course I don't want him to see this.
So this is the function in my controller to his 'my thread' page:
public function startpage($id)
{
// $userthreads = Thread::query()->where('user_id', $id)->get();
// return $userthreads;
try {
return view('test.startpage', [
'userthreads' => Thread::query()->where('user_id', $id)->get(),
'user' => User::query()->findOrFail($id)
]);
} catch (ModelNotFoundException $e) {
return view('test.notfound');
}
}
with the first two ( uncommented ) lines, I checked if there was something in the array. I just got
'[]'
as an output. That means the array is empty. I returned the $userthreads variable to the view and on my view I did this to avoid the problem:
#if(empty($userthreads))
Add Thread
#else
#foreach($userthreads as $uthread)
<ul>
{{$uthread->thread}}
</ul>
#endforeach
#endif
This haven't worked for me and I can't see why. Maybe someone of you can help me there.
Thanks for any help!
Current code of Alexey Mezenin answers:
public function startpage($id)
{
try {
$arr = [];
$arr['userthreads'] = Thread::where('user_id', $id)->get();
$arr['user'] = User::findOrFail($id);
return view('test.startpage', $arr);
} catch (ModelNotFoundException $e) {
return view('test.notfound');
}
}
HTML:
#if(count($userthreads) > 0)
Thread hinzufügen
#else
#foreach($userthreads as $uthread)
<ul>
{{$uthread->thread}}
</ul>
#endforeach
#endif
Error :
Trying to get property of non-object (View: /var/www/laravel/logs/resources/views/test/startpage.blade.php)
Ok, we discussed it in chat and found a problem:
#if(Auth::user()->id == $userthreads->first()->user_id)
Error is in your startpage.blade.php here
#if( Auth::user()->id == $userthreads->first()->user_id)
And change it like below
#if( isset($userthreads) && count($userthreads) > 0 && Auth::user()->id == $userthreads->first()->user_id)
that's it
#if(isset($userthreads) && count($userthreads) > 0)
#foreach($userthreads as $uthread)
<ul>
{{$uthread->thread}}
</ul>
#endforeach
#else
Thread hinzufügen
#endif
#ItzMe488
I think replacing the following code :
#if( Auth::user()->id == $userthreads->first()->user_id)
with
#if( Auth::user()->id == $user->first()->user_id)
should work without any errors and bugs.
Explanation:
In our chat #AlexeyMezenin found out that the error is because $userthreads is empty and $userthreads->first() errors out because of that. I think since you are passing $user also into the template, using that we can authenticate for the current user and this should prevent user B from creating threads in User A's page.
Related
my view page:
#if(empty($data))
<p>No response have been attached to this entities.</p>
#else
<p>By default, it will respond with the predefined phrases. Use the form below to customize responses.</p>
#endif
controller:
public function queries($companyID, $entityType, $entityValue)
{
$data = [];
$details = DiraQuestion::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($details AS $datum)
{
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['question'][$datum->queries] = $datum->id;
}
$detailsAns = DiraResponses::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($detailsAns AS $datum)
{
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['answer'][$datum->reply] = $datum->id;
}
ksort($data);
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
}
I made the controller and view shown above, but I can't seem to figure out what the problem is when there is no data it still shows like this:
I am trying to have it show the data but when there isn't data then for it to show something else.
I have two examples of with and without data when I dd();
first with data:
second without data:
so the one without data should shows something else like an error message.
$data is not empty in both cases, you need to be checking the answer index:
#if(empty($data['answer']))
<p>No response have been attached to this entities.</p>
#else
<p>By default, it will respond with the predefined phrases. Use the form below to customize responses.</p>
#endif
edit
You've also got an empty string index wrapping both answer and question so
#if(empty($data['']['answer']))
because you use empty() function to check data,but in controller $data is array, so It always not empty.
You can change empty() function to count() function. If $data is empty or null, it will be equal zero.
#if(count($data)==0)
<p>No response have been attached to this entities.</p>
#else
<p>By default, it will respond with the predefined phrases. Use the form below to customize responses.</p>
#endif
Consider the manual authentication. If the order ID has not been found in database, we redirect user to page with input fields and with error 'wrongOrderId':
public function login(Request $request) {
$inputted_orderId = $request->input('order_id');
$orderIdInDB = DB::table(self::SITE_IN_DEVELOPMENT_TABLE_NAME)
->where(self::ORDER_ID_FIELD_NAME, $inputted_orderId)->first();
if (is_null($orderIdInDB)) {
return Redirect::route('loginToSitesInDevelopmentZonePage')->withErrors('wrongOrderId');
}
}
In this example, we don't need to pass the error message: the message box is already exists in View; all we need is to display this message box when user has been redirected with error 'wrongOrderId':
#if (!empty($errors->first('wrongOrderId')))
<div class="signInForm-errorMessagebox" id="invalidID-errorMessage">
<!-- ... -->
</div>
#endif
All above code is working without laravel/php errors; I get into is_null($orderIdInDB) if-block when input wrong order number, however the error message box don't appears. I tried a lot of ways, and (!empty($errors->first('wrongOrderId'))) is just last one. What I doing wrong?
Did you try printing {{$errors->first()}}?
first(string), works as a key value pair, it invokes its first key VALUE
try this,
#if($errors->any())
<div class="signInForm-errorMessagebox" id="invalidID-errorMessage">
<!-- ... -->
</div>
#endif
If you want to get specific error from validator error, use the get() method.
$errors->get('wrongOrderId'); get all the wrongOrderId errors.
$errors->first('wrongOrderId'); get first error of wrongOrderId errors
I explored that $errors->first('wrongOrderId') has non-displayable but non-null value. So #if ( $errors->first('wrongOrderId') !== null ) will work.
Something more elegantly like #if ($errors->first('wrongOrderId'))? Unfortunately just one this check is not enough: even if we define
return Redirect::route('loginToSitesInDevelopmentZonePage')->withErrors(['wrongOrderId' => true]);
php will convert true to 1. So, #if ( $errors->first('wrongOrderId') == true ) will working, but #if ($errors->first('wrongOrderId')) will not.
However, we can to cast $errors->first('wrongOrderId') to bool, so the most elegant solution will be
#if ((bool) $errors->first('wrongOrderId'))
I have this function in the controller.
public function newsedit($id)
{
$editNews = $this->agro->find($id);
//return $editNews;
return Redirect::back()->with('editNews',$editNews);
//return View::make('agro.show')->with('editNews',$editNews);
}
The return $editNews displays data, so there is data in $editNews.Now i am trying to pass the same data to the view using redirect as shown in the above code.
But apparently the value is not passed. The following code shows the value is not availabel in the view
#if(isset($editNews))
<h1> value availabel</h1>
#else
<h1> No value </h1>
#endif
It displays No value . Please help me pass the data to view.I don't understant where have i gone wrong.
Laravel 4:
#if(Session::has('editNews'))
Laravel 5:
#if(session()->has('editNews'))
If you want to get the data, replace has() with get()
return View::make('agro.show', ['editNews' => $editNews]);
You can simply use
#if( Session::get( 'editNews' ) )
// show something
#endif
in Laravel 4 - it will return false to the #if block if the variable is not set
Simple view not rendering:
public function getFranchise() {
echo 'getFranchise';
$franchiseData['shopViews'] = array(1 => 'a');
$franchiseData['aaa'] = 'bbb';
return View::make('test.filteredData.franchise', $franchiseData);
}
view in test/filteredData/franchise.blade.php
franchise
{{--$shopsViews}} {{-- Fatal error: Method Illuminate\View\View::__toString() must not throw an exception in D:\projektai\dashboard\app\storage\views\d2973247ea68aed2fdfd33dc19cccada on line 5}}
{{ $aaa }}
#foreach ($shopsViews as $shop)
<strong>aaa</strong>
#endforeach
Only word getFranchise is displayed which means controller function is called. No any errors, no anything. WHat is that?
Even in constructor is added
ini_set("display_errors", true);
Edited
Found that this:
{{--$shopsViews}} {{-- Fatal error: Method Illuminate\View\View::__toString() must not throw an exception in D:\projektai\dashboard\app\storage\views\d2973247ea68aed2fdfd33dc19cccada on line 5}}
comment was causing stop of execution in the script. WHy is that? this is valid laravel comment. Also I noticed weird thigs when I comment
<?php //print_r ?>
then it shows something like web page not found, like interent connection has gone. I dont get at all whats happening with commenting.
Your blade view must contain #extends() and #section() to work in this case.
And comment should look like this {{-- $shopsViews --}}. That should fix your problem.
#extends('your_layout_folder.layout')
#section('content')
#foreach ($shopsViews as $shop)
<strong>aaa</strong>
#endforeach
#stop
Please follow the documentation! http://laravel.com/docs
I'm creating a website with laravel and when a user edits their details it will access the controller update them and redirect to the 'edit' page using this
return Redirect::to('/member/editprofile')->with('message', 'Information Changed');
this part works fine, it redirects and sends the message which is printed out on the page with this
{{ Session::get('message') }}
I was wondering if there was a way to add a class to the session? I'm probably missing something completely obvious here and this is what I tried...
{{ Session::get('message', array("class" => "success")) }}
//added the class as you would with a HTML::link
any help is appreciated, thanks in advance!
You want this
<div class="success">{{ Session::get('message') }}</div>
In Laravel-4, the Session::get accepts two arguments :
$value = Session::get('key', 'default');
$value = Session::get('key', function() { return 'default'; });