Xitish
Xitish

Reputation: 325

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('App\Student');
}

In Student Model

public function books()
{
    return $this->hasMany('App\Book');
}

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: Illuminate\Database\Eloquent\Builder::$id"

What is going wrong?
Is there a better way of doing this?

I am using Laravel 5.6

Upvotes: 0

Views: 104

Answers (1)

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

$student = Student::where('roll_no','=',$roll)->first();
$book = Book::where('book_id','=',$bookno)->first();

change like this way hope it will work .

Upvotes: 1

Related Questions