Call to a member function isEmpty() on a non-object? - laravel

I make my view in the controller via:
$data = Lib::index();
$view = View::make('index')
->with('data', $data)
->render();
return $view;
I can check if data is empty in the controller via:
$data->isEmpty();
But when I try the same thing in the view I get the error:
Call to a member function isEmpty() on a non-object
Why?
Here's the code for Lib::index():
$page = isset($_GET['page']) ? ($_GET['page']) : 1;
Paginator::setCurrentPage($page);
try {
$data = Asset::with(array('sizes'=> function($query){
$query->select('width', 'height', 'asset_id');
}))->where('active', 1)->orderBy('updated_at', 'DESC')->paginate(Config::get('p.results_per_page'), array('id', 'alt'));
}
catch (QueryException $e) {
App::abort(404);
}
return $data;

isEmpty() is a Collection method. For some weird reasons, in views, it sometimes refer to an empty Collection as null. The safest check, in my opinion would be to do a counts check, like so:
if (count($data)) {...}
This works well both in Controllers and Views.

consider you are getting some information as collection;
$UserInfo = User::where('phone', $phone_number)->first();
use this code to for error check
if(empty($UserInfo)){
return redirect()->back()->withErrors('we don't have a user with this phone number ');
}
and add below code into your blade
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
best regards

Try
> var_dump($data);
in the view.
See what it shows up. This might help further investigate the error.
Then In accordance go ahead with
> foreach($data as $moredata){
> $moredata->isEmpty(); }
Should work.

Related

Problem on setting error message if insert fails

When doing add activity inside store method, after passing validation I am calling a method that returns success or failure.
But on failure, I am not able to handle the code properly.
If I redirect, am not getting the old value.
So How do i return to create method with error message & old value both?
Any way to populate the $errors array?
Am new to Laravel. Thanks in advance
public function store(Request $request, AppMailer $mailer)
{
$validatedData=$request->validate([
.......
........
]);
$tracking_model = new Tracking;
$result = $tracking_model->add($request->all());
if ($result === true) {
return redirect('posts')->with('success', 'Created Successfully');
}
else{
$err_msgs = $result;
//what to do here ???????
// return redirect('posts/create')->with('error', $err_msgs);
}
}
try this
in the controller
return redirect('posts/create')->withInput()->withErrors($err_msgs);
and in view .blade
#if ($errors->any())
#foreach ($errors as $error)
...
#endforeach
#else
No tags
#endif

Method Illuminate\Database\Eloquent\Collection::links does not exist

I created a model relationship between User and Message. I want to implement a list of messages for the authenticated user but I get the following error.
Method Illuminate\Database\Eloquent\Collection::links does not exist
Controller
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $user->message);
}
Message provider
class message extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
User provider
public function message ()
{
return $this->hasMany('App\Message');
}
index.blade.php
#extends('layouts.app')
#section('content')
<h1>messages</h1>
#if(count($messages)>0)
#foreach ($messages as $message)
<div class="well">
<h3>{{$message->user}}</h3>
<small>Written on {{$message->created_at}} </small>
</div>
#endforeach
{{$messages->links()}}
#else
<p> no post found </p>
#endif
#endsection
Error
"Method Illuminate\Database\Eloquent\Collection::links does not exist.(View: C:\xampp\htdocs\basicwebsite\resources\views\message\index.blade.php)"
Check your view blade, that method (links()) only could be used when your data model is implementing paginate() method.
If you dont use paginate(), remove this part:
{{$messages->links() }}
If you are trying to paginate your data when it gets to the view then you need to add the paginate in your controller before passing the data to the view. Example
return $users = Users::select('id','name')->paginate(10);
with that paginate method in your controller, you can call the links method to paginate your object in view as shown below
{{$users->links()}}
hope it helps you
There are 2 ways to resolve this issue:
Either use paginate function while searching data from database:
$users = DB::table('users')->where('id',$user_id)->paginate(1);
Remove links() function from index.blade.php
{{ $messages->links() }}
Remove {{ $messages->links() }} to in your index.blade.php because {{ $messages->links() }} is supported only when you use paginate
You can do something like this in your controller file.
public function index()
{
$messages = Message::all()->paginate(5);
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $messages, $user->message);
}

How to pass extra data after validation?

After validation I want to pass some extra data to view. However, I can't send it.
My controller is like,
public function test()
{
$validator = Validator::make(
request()->all(),
[ 'ziptest' => 'regex:/^([0-9]{3}-[0-9]{4})$/']
);
$errors = $validator->errors();
if($errors->any()) {
return back()
->withErrors($errors)
->withTitle('Data From Controller')
->withInput();
}
return 'success';
}
In my blade I want to check if the title is passed or not. So in my blade view I have
#if($errors->any())
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
#endif
#if(isset($title))
<p>{{ $title }}</p>
#endif
However, the error portion is displaying properly. But not the title. Why is it not working?
I also tried sending the title in this way.
return back()->withErrors($errors)
->with('title','Data From Controller')
->withInput();
It is also not working.
I searched in the SO and found several similar questions regarding passing data from controller to view. However, my situation is a bit different.
In your example, you are redirecting back to the previous location. When you use with* for a redirect the information is flashed to the session, rather than made directly available to the view like it would be if you were returning a view instead.
For it to work with your example, you would have to check session('title') to get the flashed title from the redirect.
Your second approach is almost correct.
return back()->withErrors($errors)
->with([
'title' => 'Data From Controller'
])
->withInput();
note the array notation
use here array_merge method
$errors = $validator->errors();
if($errors->any()) {
$newErrors = array_merge($errors->toArray(),['title' => 'Data From Controller']);
return back()
->withErrors($newErrors)
->withInput();
}
Did you tried after validation hook but it will return data as in error bag
$validator->after(function ($validator) {
$validator->errors()->add('someField', 'Somedata');
});
And i'm wondering from where are you calling view because i saw your test() method do only validation part, with you're view you can pass data with it but with validation i think as in error bag you can send data to view.

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.

Handling errors when variable is null - Laravel

I'm querying a model in a method in my controller to get all messages.
public function index(){
$messages = Message::where('sender_id', Auth::user()->id)->orWhere('recipient_id', Auth::user()->id)->get();
return view('/pages/message/index', compact('messages'));
}
If the model is null and has now entries, I get an error of 'can get method of non object or something like that.
What's the best way to handle errors like this. Ideallly in the controller
#if($messages)
//Codes
#endif
if collection in loop. Forelse statement is cool for that.
#forelse ($messages as $message)
<li>{{ $message->content }}</li>
#empty
<p>There is no messages</p>
#endforelse
in your view
#if(count($messages)>0)
//your code
#endif
or
#if(!empty($messages))
//your code
#endif

Resources