Courses

Build Laravel API for Car Parking App: Step-By-Step

As in every application, users should be able to update their profile. Personally, I like to separate two actions: change profile details and change password.

So, I vote for these API endpoints:

  • GET /profile - to view profile details
  • PUT /profile - to update name/email
  • PUT /password - to update the password

You could also make both PUT actions into one endpoint, with an if-else statement, but I personally like the separation of those concerns.


Get/Update Profile

Let's generate a Profile Controller - this time with two methods in it.

I will still keep the namespace of Auth because those features are related to the authenticated users.

php artisan make:controller Api/V1/Auth/ProfileController

This will be the code inside.

app/Http/Controllers/Api/V1/Auth/ProfileController.php:

namespace App\Http\Controllers\Api\V1\Auth;
 
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\Rule;
 
class ProfileController extends Controller
{
public function show(Request $request)
{
return response()->json($request->user()->only('name', 'email'));
}
 
public function update(Request $request)
{
$validatedData = $request->validate([
'name' => ['required', 'string'],
'email' => ['required', 'email', Rule::unique('users')->ignore(auth()->user())],
]);
 
auth()->user()->update($validatedData);
 
return response()->json($validatedData, Response::HTTP_ACCEPTED);
}
}

Not sure I need to explain much here: in the show() method we just show a few fields of a logged-in user (we don't show any ID or password-sensitive fields), and in the update() method we validate the data, update the DB row and return the updated data as JSON.

Now, the most important part: how do we get that auth()->user() or $request->user() automatically?

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 59 courses (1057 lessons, 42 h 44 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord