I know you can get the last inserted id using this $insertedId = $user->id;
But I'm trying to get the last inserted value in my view for each sender who sends the data. Just like a inbox it always shown the last message that sent by the sender. How can I show this in my view?
This is my POST where messaging happens.
public function postMessage(Request $request)
{
$this->validate($request,
[
'recipient' => 'required',
'message' => 'required|max: 2000',
]);
$message = new Message();
$message->message_content = $request->message;
$message->save();
$user = Auth::user();
foreach($request->recipient as $recipientId)
{
$message->users()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
return redirect()->back();
}
Retrieving the values. What I'm done here so far I just retrieve all the user's message. Still don't have an idea how to get the last inserted. Any help how can I achieve this?
public function getMessage()
{
$recipientLists = DB::table('users')->where('id', '!=', Auth::id())->get();
$messageResult = DB::table('message_user')->select('messages.message_content', 'users.username', 'messages.id')
->join('users', 'users.id', '=', 'message_user.sender_id')
->join('messages', 'messages.id', '=', 'message_user.message_id')
->where('user_id', '=', Auth::id())
->where('sender_id', '=')->get();
return view ('message.create')->with('recipientLists', $recipientLists)->with('messageResult', $messageResult);
}
Migration (Pivot table)
public function up()
{
Schema::create('message_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('message_id')->unsigned();
$table->foreign('message_id')->references('id')->on('messages')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('sender_id')->nullable();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('dateModified')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
}