I'm trying to make really simple function user to be able to message to admin only and admin to answer on this message.
So far I've made table message
with following columns
id | from_id | to_id | subject | message
In the controller I have this which should select all messages which are sent to current logged in user ( not sure if is correct )
public function index(){
//$messages = Message::latest()->get();
$currentUser = Auth::user()->id;
$messages = Message::
whereRaw('message.id = (select max(id) from `message` m2 where m2.to_id = '.$currentUser.')' )
->orderBy('id', 'desc')
->get();
return view('test.index', compact('messages'));
}
Now I'm trying to make viewMessage
function
In index blade this is the link to single message
{!! link_to('test/view/' . $message->from_id, $message->subject) !!}
My Route
Route::get('test/view/{id}', 'MessageController@messageView')->name('test.view');
And controller function
public function messageView($id) {
$user = User::where('id', $id)->first();
$messages = $user->messages()->orderBy('created_at', 'asc')->get();
return View::make('test.view', compact('messages'));
}
When I click on the button I got this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'message.user_id' in 'where clause' (SQL: select * from
message
wheremessage
.user_id
= 4 andmessage
.user_id
is not null order bycreated_at
asc)
In User model I've added relation to message like:
public function messages() {
return $this->hasMany('App\Message');
}
And in Message model
public function user(){
return $this->belongsTo('App\User');
}
My question why in the query is looking for user_id when on my button I send from_id and how to fix this?
Why in the query is looking for
user_id
You need to add foreign key and ID to the relationship to fix the error, for example:
public function messages() {
return $this->hasMany('App\Message', 'from_id', 'id');
}