Handling errors when variable is null - Laravel - 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

Related

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

Get related objects on the view

I have related model
class Myevent extends Model
{
public function photo()
{
return $this->hasMany('App\EventPhoto');
}
}
Ob blade if loop i get items Myevents
#foreach($evetns as $event)
<b>{{$event->name}}</b> <br>
{{$event->place}} <br>
{{$event->description}} <br>
#foreach($event->photo() as $item)
{{$item->id}}
#endforeach
#endforeach
How can I call related objects in a loop on blade?
You seem to be doing correctly, except for one single error $event->photo instead of $event->photo()
#foreach($event->photo as $item)
{{$item->id}}
#endforeach
To clear the confusion regarding brackets https://laraveldaily.com/calling-eloquent-from-blade-6-tips-for-performance/

How to set null if relations doesn't exist?

In Model I have:
public function publisher()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
In template blade I try to show data User:
#foreach($announcement->offers as $key => $item)
<img src="{{url($item->publisher->photo)}}">
#endforeach
The Problem is that if there is no data in the User table, the program crashes because I can not get the property $item->publisher->photo.
How to fix it?
You can do something like this:
#if (empty($item->publisher))
It's empty
#else
<img src="{{ url($item->publisher->photo) }}">
#endif
Working on memory here, but you could use #forelse/ #empty. These directives can be used if the object your'e iterating over is empty:
#forelse($announcement->offers as $key => $item)
<img src="{{url($item->publisher->photo)}}">
#empty
//default image or message?
#endforelse
https://laravel.com/docs/5.4/blade#loops

Laravel: Why isn't the query result showing in my view?

I am successfully getting results in/from my controller like this:
$session_id and $user_id are getting passed into my method.
Controller
// get all sets belonging to the user for the given session
$session = Session::findOrFail($session_id);
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id);
$user = User::findOrFail($user_id);
return View('users.index')
->with('session', $session)
->with('sets', $sets)
->with('user', $user);
View
<p>{{ $user->first_name }} has {{ $sets->count() }} existing set{{ ($sets->count() > 1 ? 's': '') }}.</p>
<ul class="list-unstyled">
#foreach ($sets as $set)
<li>
Set
</li>
#endforeach
</ul>
I am seeing "Foo has 1 existing set." and I can see the record in the DB. However, I'm not getting into the loop at all. If I add/remove records, my paragraph text updates accordingly as well - but I still never get into the loop to show each set. I'm sure it's something obvious, but I sure don't see it.
Thank you for any suggestions!
Change the query of sets to this:
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id)->get();
As get() method will return you the collection object.

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

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.

Resources