Home > Back-end >  How to display and update input values from the database on Laravel
How to display and update input values from the database on Laravel

Time:10-11

Am displaying user profile data from the database to an input field and at at the same time, the user should be able to update the input field

Controller.php

// shows details in input 
Public function details()
{
    $id = auth()->id;
    $details=Users::where(‘id’,’=‘,$id)->first();

return view (‘profile’,compact(‘details’);
}

// Update function 

Public function details()
{
    // I don’t know what to do
}

blade.php

<form action=‘{{ route(‘update’) }} method=‘post’>
@csrf
<input type=‘text’ name=‘firstname’ value=‘{{ $details->firstname}}’ >

<input type=‘text’ name=‘lastname’ value=‘{{ $details->lastname}}’ >

<input type=‘submit’ value=‘Submit’ >
</form>
    

CodePudding user response:

first change second function name to different name for example update

Public function update(Request $request)
    {
        Auth::user()->update([
    'firstname'=> $request->firstname,
    'lastname' => $request->lastname
    ]);
    return redirect()->back();
    }

CodePudding user response:

use Illuminate\Http\Request;

Public function details(Request $request, User $user)
{
 
    $user->firstname = $request->firstname;
    $user->lastname = $request->lastname;
    $user->save();
}

route:

Route::put('/user/{user}', ...);

blade:

<form action=‘{{ route(‘update’, $details->id) }} method=‘post’>
@csrf
{{method_field('PUT')}}
<input type=‘text’ name=‘firstname’ value=‘{{ $details->firstname}}’ >

<input type=‘text’ name=‘lastname’ value=‘{{ $details->lastname}}’ >

<input type=‘submit’ value=‘Submit’ >
</form>
  • Related