개발 환경
Windows
PHP 8.2
Laravel 9.*
미들웨어를 이용해 게시글 작성자만 게시글 url에 접속할 수 있도록 작업하는 도중에 'Call to a member function setCookie() on null' 오류가 발생했다.
번역하면 "null에 대해 setCookie() 멤버 함수를 호출했습니다" 라는 뜻이다.

오류가 발생한 코드는 다음과 같다.
<?php
namespace App\Http\Middleware;
use App\Models\Board;
use Illuminate\Http\Request;
use Closure;
class CheckBoardOwnership
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next)
{
$boardId = $request->route('board');
$board = Board::find($boardId);
if ($board && $board->user_id === auth()->id()) {
return view('board.show', compact('board'));
}
abort(403, 'Unauthorized');
}
}
이 오류는 PHP에서 객체의 메소드를 호출할 때 해당 객체가 null인 경우에 발생한다.
오류가 발생하는 이유는 다음과 같다.
1. 객체의 초기화가 실패한 경우
예를 들어 객체를 생성하려는 도중 오류가 발생하여 객체가 생성되지 않았거나 초기화되지 않은 경우에 해당 객체가 null로 설정될 수 있다.
이 경우에는 해당 객체의 메소드를 호출할 때 "Call to a member function..." 오류가 발생할 수 있다.
2. 변수에 잘못된 값이 할당된 경우
객체를 예상했지만 실제로는 null이 할당되었을 때 오류가 발생한다.
이는 변수의 값을 확인하지 않고 객체의 메소드를 호출하여 발생하는 오류다.
3. 의도하지 않은 논리 흐름
예상치 못한 논리 흐름으로 인해 객체가 null로 설정될 수도 있다.
이는 프로그램의 버그나 오류로 인해 발생한다.
따라서 이 오류가 발생한 경우, 코드에서 해당 호출이 이루어지는 부분을 검토하고, 해당 객체가 null이 될 수 있는지 확인해야 한다.
객체의 초기화 과정을 확인하고 변수에 적절한 값이 할당되는지 확인하여 오류를 해결한다.
내 경우에는 2번 문제였다.
다음과 같이 response() 함수를 추가하여 문제를 해결했다.
<?php
namespace App\Http\Middleware;
use App\Models\Board;
use Illuminate\Http\Request;
use Closure;
class CheckBoardOwnership
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next)
{
$boardId = $request->route('board');
$board = Board::find($boardId);
if ($board && $board->user_id === auth()->id()) {
return response()->view('board.show', compact('board'));
}
abort(403, 'Unauthorized');
}
}
'response()'는 Laravel의 글로벌 헬퍼 함수 중 하나이다.
HTTP 응답(Response)을 생성하기 위한 'response' 팩토리를 반환한다.
여기서 글로벌 헬퍼 함수(Global Helper Functions)는 프레임워크나 라이브러리에서 전역적으로 사용할 수 있는 함수를 의미한다.
이러한 함수들은 어떤 클래스에도 속하지 않고, 어디서든 호출할 수 있다.
참고
https://stackoverflow.com/questions/48970172/call-to-a-member-function-setcookie-on-null
Call to a member function setCookie() on null
I am trying to finish this middleware in larval that checks to make sure is subscribed to a subscription plan. If the user is not it redirects to the payment page. public function handle($request,
stackoverflow.com