Laravel Creating relationship while updating
I have a library management system with Student and Book model. The structure of the tables are
Students Table
id | roll_no | name | created_at | updated_at
Books Table
book_id | name | author | publication | student_id | created_at | updated_at
Here, boook_id
is the primary key
The relation is as follows
In Book Model
public function student()
{
return $this->belongsTo('AppStudent');
}
In Student Model
public function books()
{
return $this->hasMany('AppBook');
}
Initially the student_id
in books table is null
. Whenever a book is to be issued, book number
and student roll number
is supplied and the student_id
field in books table is updated with the id
of the student to whom it is being issued.
In the controller, I have the following code
public function postIssue(Request $request)
{
$this->validate($request, [
'rollno' => 'required|min:7',
'bookno' => 'required|numeric',
]);
$roll = $request->input('rollno');
$bookno = $request->input('bookno');
$student = Student::where('roll_no','=',$roll);
$book = Book::where('book_id','=',$bookno);
$book->student_id = $student->id;
$book->save();
return view('book.issue')->with('msg','Book Issued');
}
When I run this codes, I get a error saying
"Undefined property: IlluminateDatabaseEloquentBuilder::$id"
What is going wrong?
Is there a better way of doing this?
I am using Laravel 5.6
from Laravel Questions and Answers https://laravelquestions.com/php/laravel-creating-relationship-while-updating/
via Lzo Media
No comments:
Post a Comment