0

I am developing a website using Laravel and Ajax. I have a problem when I try to return all messages (Messages model) that belong to specific user (User model) using hasMany method.

web.php

Route::get('/test', 'UserController@testFunction');
Route::post('/test', 'UserController@testFunction');

UserController.php

public function testFunction(Request $request) {
    if ($request->isMethod('post')) {
        $messages = User::find(1)->messages;
        return $messages;
    } else {
        return 'get method';
    }
}

User model

class User extends Authenticatable {
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function messages() {
        $this->hasMany('App\Message', 'from');
    }
}

Message model

class Message extends Model {
    protected $fillable = [
        'from', 'to', 'content'];
}

Then I have two buttons (just for testing - POST and GET). They are handled by this JavaScript code

window.onload = function() {
    // AJAX Setup
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // Post Method
    $('#postMethod').click( function() {
        $.post('test', function (data) {
            console.log(data);
        });
    });

    // Get Method
    $('#getMethod').click(function() {
        $.get('test', function(data) {
            console.log(data);
        });
    });
}

Tables in the databse have a structure as shown below:

When I click on POST button (handled by above javascript code), I receive this error in console: error in console

If I change $messages = User::find(1)->messages; to $messages = User::find(1)->name;, for example, I get the name of the user with ID 1 returned to the console normally.

I assume that something is wrong with messages() function in UserController.php. Maybe 'from' as foreign key? This is just my guess, maybe the error is somewhere else, please take a look yourself.

2 Answers2

0

test with /. Try this

// Post Method
    $('#postMethod').click( function() {
        $.post('/test', function (data) {
            console.log(data);
        });
    });

    // Get Method
    $('#getMethod').click(function() {
        $.get('/test', function(data) {
            console.log(data);
        });
    });
Ilya Yaremchuk
  • 2,007
  • 2
  • 19
  • 36
0

Here is your fix, you need to call messages like this messages() that will return relationship instance.

public function testFunction(Request $request) {
if ($request->isMethod('post')) {
    $messages = User::find(1)->messages();
    return $messages;
} else {
    return 'get method';
}
}

Hope this helps.

Faraz Irfan
  • 1,306
  • 3
  • 10
  • 17
  • Thank you! This solves the error - it is no longer present. But the problem is that I am not getting any data back, even though it should return a message. This is my messages table data: [link](http://shrani.si/f/3t/Pb/2cXrIofy/table.jpg). As you can see, I have one message that belongs to user with ID of 1, but it isn't returned to the console. Is my `public function messages()` written correctly, especially the second parameter? – brainstorm Feb 23 '18 at 12:42
  • Try this `$messages = User::find(1)->messages()->get();` – Faraz Irfan Feb 23 '18 at 12:52
  • If I add `get()` method, I get `POST 500 (Internal Server Error)` error again. – brainstorm Feb 23 '18 at 12:59
  • Ok, you can also do this in that way `User::where('id',1)->with('messages')->get();` , let me know If this works. – Faraz Irfan Feb 23 '18 at 13:05
  • No, it gives `POST 500 (Internal Server Error)` error again. Is `with('messages')` part correct? – brainstorm Feb 23 '18 at 13:10
  • Can you show me what exactly error/exception you got ? – Faraz Irfan Feb 23 '18 at 13:12
  • Console output: [link](http://shrani.si/f/R/vr/1XkwBUiU/console.jpg). Network tab output: [link](http://shrani.si/f/3Y/Ab/2ErIwtFw/network.jpg). – brainstorm Feb 23 '18 at 13:17
  • You are missing a return statement in your messages relation, it would be like this `return $this->hasMany('App\Message', 'from');` – Faraz Irfan Feb 23 '18 at 13:21