i’m facing an error Call to a member function subjects() on null . My project is by php and laravel. My project is on live server. Its works fine normally but when i click to edit something or click update button then it shows Call to a member function subjects() on null . Only my current browser facing this error but if i hit from another browser to my server its seems ok.
public function index()
{
$featured_packages = Package::where('featured_package', 1)
->with('reviews', 'user')
->get();
$popular_packages = Package::where('popular_package', 1)
->with(['class' => function ($query) {
$query->pluck('name');
}, 'reviews', 'user'])
->withCount('mcqs')->get();
$class_id = StudentClass::all()->random()->id;
if (Auth::check()) {
$class_id = auth()->user()->grad != '' ? auth()->user()->grad : $class_id;
}
$subjects = StudentClass::find($class_id)->subjects()->withCount('packages')->get();
return view('frontend.index', compact('featured_packages', 'popular_packages', 'subjects', 'class_id'));
}
public function about()
{
$about = About::orderBy('id', 'desc')->first();
return view('frontend.about', compact('about'));
}
public function contact()
{
return view('frontend.contact');
}
public function faqs()
{
$faqs = Faq::orderBy('id', 'asc')->where('status', 1)->get()->groupBy('tab');
return view('frontend.faqs', compact('faqs'));
3
Answers
Use
findOrFail()
instead offind()
, or just check it with conditional statement. YourStudentClass::find($class_id)
could be null and it is worth to check it before chaining.Check if StudentClass exist first
Following the Laravel documentation, you need to use the method
findOrFail()
like this :Because if your
StudentClass
isn’t found, you can’t use your functionsubjects()
onnull
.