Getting error of 'Trying to get property 'course_code' of non-object' when i click my edit button. what could be the problem?

238 views Asked by At

I am trying to edit the entry into the table, but every time I click my edit button to take me to the edit page it gives me the error:

Trying to get property 'course_code' of non-object

Below is my code:

CourseController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Course;

class CoursesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // $courses = Course::all();

        // $courses = Course::orderBy('title', 'desc')->get();
        $courses = Course::orderBy('course_code', 'desc')->paginate();
        return view('subs.index')->with('courses', $courses);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('subs.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'course_code' => 'required',
            'course_name' => 'required'
        ]);

        $course = new Course;
        $course->course_code = $request->input('course_code');
        $course->course_name = $request->input('course_name');
        $course->save();

        return redirect('/subs')->with('success', 'New course added!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($course_code)
    {
        $course = Course::find($course_code);
        return view('subs.show')->with('course', $course);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($course_code)
    {
        $course = Course::find($course_code);
        return view('subs.edit')->with('course', $course);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $course_code)
    {
        $this->validate($request, [
            'course_code' => 'required',
            'course_name' => 'required'
        ]);

        $course = Course::find($course_code);
        $course->course_code = $request->input('course_code');
        $course->course_name = $request->input('course_name');
        $course->save();

        return redirect('/subs')->with('success', 'Course Updated!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

show.blade.php:

@extends('layouts.app')

@section('content')
<a href="/subs" class="btn btn-default">Go back</a>
    <div class="container">
        <h1>{{$course->course_code}}</h1>
        <h3>{{$course->course_name}}</h3>
    </div>
    <a href="/subs/{{$course->course_code}}/edit" class="btn btn-default">Edit</a></td>
@endsection

edit.blade.php:

@extends('layouts.app')

@section('content')
    <a href="/subs" class="btn btn-default">Go back</a>
    <div class="container" style="width:50%; margin-left:350px;margin-top:20px">
        <h1>Edit Course</h1>
        {!! Form::open(['action' => ['CoursesController@update', $course->course_code], 'method'=>'POST']) !!}
            <div class="form-group">
                {{Form::label('course_code', 'Course code')}}
                {{Form::text('course_code', $course->course_code,['placeholder'=>'Course code', 'class'=>'form-control col-md-3'])}}
            </div>
            <div class="form-group">
                {{Form::label('course_name', 'Course name')}}
                {{Form::text('course_name', $course->course_name,['placeholder'=>'Course name', 'class'=>'form-control col-md-7'])}}
            </div>
            {{Form::hidden('_method', 'PUT')}}
            {{Form::submit('Add Course',['class'=>'btn btn-primary'])}}
        {!! Form::close() !!}
    </div>

@endsection

my model code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    //
}

Where did I go wrong and how can I fix this error?

3

There are 3 answers

1
Jerodev On BEST ANSWER

The ::find() method will only return objects with a matching primary key, you cannot pass other values. If not object is found with this primary key, null will be returned and you can't get a property from null.

Either change your primary key, or better, update your query:

$course = Course::where('course_code', $course_code)->first();

It's also a good idea to add a check if the query actually returned something. Just to be sure to avoid the same error in the future:

if ($course === null) {
    abort(404); // Show 404 page if course does not exist
}

If you change the primary key, don't forget to update the following properties on your Course model.

// The column name of your primary key.
protected $primaryKey = 'your_key_name';

// Indicating that the primary key is not a number.
public $incrementing = false;
0
albus_severus On

I think here course_code is not primary key..so you can't get it by using find Two ways.

1st passing your primary key(**id**) & update

2nd using where

$course = Course::where('course_code',$course_code)->first();

then update. here you want to change the value of course_code also.so 1st one is correct for you passing id & use find & update that

0
lagbox On

You are using the wrong value to generate links for your model. You need to be using the id not course_code. The find method will use the primary key of the model to do its search.

<a href="/subs/{{ $course->id }}/edit" class="btn btn-default">Edit</a>

Now you are passing the correct value for the parameter so you can use find on the model. If you want to use a different value other than id you can do that but you have to adjust your query to find it by a different field.

If you keep using course_code instead of id you just have to search based on that field:

$course = Course::where('course_code', $course_code)->first();