Search code examples
laravelpostman

{ "message": "Unauthorized. Please log in to create a post."


I want to make a post using postman but everytime i send a post it says'Unauthorized. Please log in to create a post'but I have already loged in this is the laravelcode postcontroller

On the postcontroller the store method was sited to be the issue earlier where the postman was showing I was trying to access null id at auth()->user() line so I created another method to first check if the user is logged in to avoid that error ut ow the error shows I am not logged in despite of logging in

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\post;

class postController extends Controller
{
    public function index()
    {
        return response([
            'posts' => post::orderBy('created_at', 'desc')
                ->with('user:id,image', 'name')
                ->withCount('comments', 'likes')->get(),
        ], 200);
    }



    public function show($id)
    {
        return response(['post' => post::where('id', $id)->withCount('likes', 'comments')->get()], 200);
    }

    //create a post
    public function store(Request $request)
    {
        $attrs = $request->validate([
            'body' => 'required|string',
        ]);


        if (auth()->check()) {
            $user_id = auth()->user()->id;
            $post = post::create([
                'body' => $attrs['body'],
                'user_id' => $user_id,
            ]);


            // $post = post::create([
            //     'body' => $attrs['body'],
            //     'user_id' => auth()->user()->id,
            // ]);


            return response([
                'message' => 'post created',
                'post' => $post
            ], 200);
        } else {
            return response([
                'message' => 'Unauthorized. Please log in to create a post.'
            ], 401);
        }

    }


    public function update(Request $request, $id)
    {
        $post = post::find($id);
        if (!$post) {
            return response([
                'message' => 'not found'
            ], 403);
        }

        if ($post->user_id != auth()->user()->id) {
            return response([
                'message' => 'permission denied'
            ], 403);
        }

        $attrs = $request->validate([
            'body' => 'required|string',
        ]);

        $post->update([
            'body' => $attrs['body']
        ]);


        return response([
            'message' => 'post updated',
            'post' => $post
        ], 200);
    }

    public function destroy($id)
    {
        $post = post::find($id);
        if (!$post) {
            return response([
                'message' => 'not found'
            ], 403);
        }

        if ($post->user_id != auth()->user()->id) {
            return response([
                'message' => 'permission denied'
            ], 403);
        }

        $post->coments()->delete();
        $post->like()->delete();
        $post->delete();

        return response([
            'message' => 'post deleted',
        ], 200);

    }


}

post model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\comment;
use App\Models\like;
use App\Models\User;

class post extends Model
{
    use HasFactory;
    protected $fillable = [
        'user_id',
        'body',
        'image'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);

    }
    public function comments()
    {
        return $this->hasMany(comment::class);
    }

    public function likes()
    {
        return $this->hasMany(like::class);
    }
}

post table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id');
            $table->string('body');
            $table->string('image')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('post');
    }
};


Solution

  • Make sure that you have middleware('auth:sanctum') in your route. So it would be something like:

    Route::group(
        ['middleware' => 'auth:sanctum'],
        function () {
            Route::post('/posts', [PostsController::class, 'create']);
        }
    );