skip to Main Content

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


  1. Use findOrFail() instead of find(), or just check it with conditional statement. Your StudentClass::find($class_id) could be null and it is worth to check it before chaining.

    Login or Signup to reply.
  2. Check if StudentClass exist first

    $studentClass = StudentClass::find($class_id); 
    
    if ($studentClass) {
           $subjects = $studentClass->subjects()->withCount('packages')->get(); }
    
    Login or Signup to reply.
  3. Following the Laravel documentation, you need to use the method findOrFail() like this :

    $subjects = StudentClass::findOrFail($class_id)->subjects()->withCount('packages')->get();
    

    Because if your StudentClass isn’t found, you can’t use your function subjects() on null.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search