Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Get newly inserted id from a relationship on save

I have a morphMany relationship for comments that are related to a question Model I would like to know how you get the newly inserted id when saving a new comment Model.

    public function postComment() {

    if(Request::ajax() && Auth::check()) {
        //Input::merge(array_map('trim', Input::all()));

        $comment = new Comment;
        $comment->user_id = Auth::user()->id;
        $comment->body = Helper::strip_tags(Input::get('body'));
        $question_id = Input::get('question_id');
        $question = Question::find($question_id);

        // here in the if statement how do I get the newly created id of a comment
        if($question->comments()->save($comment)) {         

            return Response::json(array('success' => true, 'body' => Input::get('body'), 
                'userlink' => HTML::linkRoute('profile', Auth::user()->username, array('id' => Auth::user()->id)), 'date' => date("F j, Y, g:i a") ));
        } else {
            return Response::json(array('success' => false, 'body' => Input::get('body')));
        }           
    }
}
like image 730
ONYX Avatar asked Jul 20 '15 23:07

ONYX


1 Answers

The saved comment record will be returned on save:

$comment = $question->comments()->save($comment);

if($comment) {
    // Comment was saved

    $comment->id;
} else {
    // Comment was not saved
}
like image 76
Steve Bauman Avatar answered Oct 09 '22 07:10

Steve Bauman