简体   繁体   中英

can't access variable in view from controller laravel

I can't access $prospectus in the function show() but works well in the function store() in laravel version 5.6.27

public function store(Request $request) {

    $course = Course::create([
        'name' => $request['name'],
        'title' => $request['title'],
        'division_id' => $request['division_id'],
    ]);

    $prospectus = Prospectus::create([
        'years' => $request['years'],
        'name' => $course->name,
        'user_id' => null,
        'course_id' => $course->id,
    ]); 

    return view('courses.show', compact('course', 'prospectus'));
}

public function show(Course $course) {
    $prospectus = Prospectus::where('course_id', $course->id)->get();

    //return $prospectus;
    return view('courses.show', compact('course', 'prospectus'));
}

the data is passed when i use return $prospectus; but not in return view('courses.show', compact('course', 'prospectus'));

here are my routes

Route::resource('courses', 'CourseController');

Route::post('courses', 'CourseController@store')->name('courses.store');

Route::get('courses/{course}', 'CourseController@show')->name('courses.show');

I supose you want a single Prospectus object, get() will give you a collection of objects.

Use the first() function to get only the first match from the database as a single object.

$prospectus = Prospectus::where('course_id', $course->id)->first();

Confirm that $prospectus query don't return NULL

Try this:

$prospectus = Prospectus::where('course_id', $course->id)->first();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM