0

I am building an application using Laravel 5.2. I'm trying to create an Edit modal using jquery. However I am getting a 500 internal server error, every time I try to update a record in the database. On further investigation using Firebug I get the error:

"Creating default object from empty value"...

These are the relevant code blocks.

Route.php - The edit route is what I'm trying to access from my modal

<?php

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    })->name('home');

    Route::post('/signup', [
        'uses' => 'UserController@postSignup',
        'as' => 'signup']);

    Route::post('/signin', [
        'uses' => 'UserController@postSignin',
        'as' => 'signin']);

    Route::get('/logout', [
        'uses' => 'UserController@getLogout',
        'as' => 'logout']);


    Route::get('/dashboard', [
        'uses' => 'PostController@getDashboard',
        'as' => 'dashboard',
        'middleware' => 'auth'
    ]);

    Route::post('/createpost', [
        'uses' => 'PostController@CreatePost',
        'as' => 'createpost',
        'middleware' => 'auth']);

    Route::get('/delete-post/{post_id}', [
        'uses' => 'PostController@getDeletePost',
        'as' => 'post.delete',
        'middleware' => 'auth']);

    Route::post('/edit', [
        'uses' => 'PostController@getEditPost',
        'as' => 'edit'
    ]);
});

PostController.php

public function getEditPost(Request $request)
{
    $this->validate($request, [
       'body' => 'required'
    ]);
    $post = Post::find($request['postid']);

    $post->body = $request['body'];
    $post->update();
    return response()->json(['new_body' => $post->body], 200);
}

The Javascript file with the click event, app.js. I am printing a message to the console upon successful update of the database

var postId = 0;
$('.post').find('.interaction').find('.edit').on('click', function (event) {
    event.preventDefault();
    var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
    postId = event.target.parentNode.dataset['postid'];
    $('#post-body').val(postBody);
    $('#edit-modal').modal();
});
$('#modal-save').on('click', function () {
    $.ajax({
        method: 'POST',
        url: url,
        data: {body: $('#post-body').val(), postId: postId, _token: token}
    }).done(function (msg) {
        console.log(JSON.stringify(msg));
    });
});

This is my view page

dashboard.blade.php

@extends('layouts.master')

@section('content')
@include('includes.message-block')
<section class="row new-post">
    <div class="col-md-6 col-md-offset-3">
        <header><h3>What do you have to say?</h3></header>
        <form action="{{ route('createpost') }}" method="post">
            <div class="form-group">
                <textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your Post"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Create Post</button>
            <input type="hidden" value="{{ Session::token() }}" name="_token">
        </form>
    </div>
</section>
<section class="row posts">
    <div class="col-md-6 col-md-offset-3">
        <header><h3>What other people say...</h3></header>
        @foreach($posts as $post)
            <article class="post" data-postid="{{ $post->id }}">
                <p>{{ $post->body }}</p>
                <div class="info">
                    Posted by {{ $post->user->first_name }} on {{ $post->created_at }}
                </div>
                <div class="interaction">
                    <a href="#">Like</a> |
                    <a href="#">Dislike</a>
                    @if(Auth::user() == $post->user)
                        |
                        <a href="#" class="edit">Edit</a> |
                        <a href="{{ route('post.delete', ['post_id' => $post->id]) }}">Delete</a>
                    @endif
                </div>
            </article>
        @endforeach
    </div>
</section>

<div class="modal fade" tabindex="-1" role="dialog" id="edit-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Edit Post</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="post-body">Edit the Post</label>
                        <textarea class="form-control" name="post-body" id="post-body" rows="5"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script>
    var token = '{{ Session::token() }}';
    var url = '{{ route('edit') }}';
</script>
@endsection

Please can anyone help me to see what I'm missing here? Thanks

1 Answer 1

1

It looks like you get null on $post = Post::find($request['postid']);.

Do some checks before trying to update the model.

You can use ::findOrFail() or check if !is_null($post).

Also you should use $request->input('postid').

Sign up to request clarification or add additional context in comments.

4 Comments

I've done some checks, $post returns null. But I cant find out why
You should figure out why it's null. Try dumping the id and checking manually in the database, if it exists.
The data exists. I was thinking perhaps I made a mistake somewhere in the form in dashboard.blade.php where I assigned postid, but everything looks find and still I get an error
@CalebOki check if your javascript sends the proper id then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.