i am getting error, Internal server error,
GET http://isp.local/teachers/168/edit 500 (Internal Server Error)
Controller:
public function edit($id)
{
$teacher = DB::table('teachers')
->find($id)
->select('*')
->first();
return response()->json([
'status' => 'success',
'teacher' => $teacher,
]);
}
while when i make following changes in controller i am getting correct results, what is issue in above code?
Controller:
public function edit($id)
{
$teacher = Teacher::find($id);
return response()->json([
'status' => 'success',
'teacher' => $teacher,
]);
}
That query is wrong. ->find() executes the query, as does ->first(), and everything is selected by default, so ->select('*') is unnecessary.
$teacher = DB::table('teachers')->find($id);
Should be enough. But you're already using the correct
$teacher = Teacher::find($id);
So there isn't much point to using the DB::table() approach.
Try
->whereId($id)
or
where('id',$id)
Related
I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):
route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
route::controller(UserController::class)->group(function () {
route::post('/register', 'register');
route::post('/login', 'login');
route::get('/logout', 'logout');
});
route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
As you can see in the image above, I can get the authenticated user after try login it, here's my login method:
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if ($validate) {
$credentials = $request->only('email', 'password');
return Auth::attempt($credentials)
? Auth::user() :
response()->json('No se ha podido iniciar sesiĆ³n', 500);
}
return response()->json($validate->errors, 422);
}
But when I'm going to store a new book, I get the following error:
Here's the error, when I try to use the auth()->user() method to get the logged in user's id:
public function store(Request $request)
{
$validate = $request->validate([
'title' => 'required',
'genre' => 'required'
]);
if ($validate) {
$book = Book::create([
'title' => $request->title,
'author' => $request->author,
'genre' => $request->genre,
'subgenre' => $request->subgenre,
'opinion' => $request->opinion,
]);
$user = User::find(auth()->user()->id);
if ($request->cover) {
$this->uploadImage($request, 'cover', $book);
}
$user->books()->save($book);
return new BooksResource($book);
}
I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:
From laravel 9 documentation
// Get the currently authenticated user's ID...
$id = Auth::id();
Also, you should describe your
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
route before resource route.
I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user
To get the Authenticated user, put the book route inside the auth:sanctum middleware.
I have already asked question about Laravel 5.7 validation, however it still does not work quite right. the validation is not executed at all when sending the content.
public function store(Request $request)
{
$data=$request->all();
$validator = Validator::make($data, [
'first_name' => 'alpha|min:2|max:30',
]);
}
Thanks in advance
if your are not using form validation then maybe it will be helpful for you.
I add validator example in your code, you can try it
maybe your problem will resolve
public function update(Request $request, Player $player)
{
//example validation
$validator = Validator::make($request->all(), [
'id' => 'required|integer', //put your fields
'text' => 'required|string' //put your fields
]);
if ($validator->fails()){
return "Invalid Data";
}
if(Auth::check()){
$playerUpdate = Player::where('id', $player->id)
->update([
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name')
]);
if($playerUpdate){
return redirect()->route('players.show', ['player'=> $player->id])
->with('success' , 'player foo');
}
}
return back()->withInput()->with('errors', 'Foo error');
}
I don't see your validation code at all.
there are two ways for implementing the validation in laravel
Form Request Validation
validation in controller methods
Please Add one, and try again
I'm developing a REST API in Laravel. I'm using route model binding to update an item. I want to return a JSON not found response when the id is not found in the database.
This is the entry in the route api.php file:
Route::get('product/{product}', 'ProductController#show')->name('products.show');
The controller update function looks as follows:
public function update(Request $request, Product $product)
{
$request->validate([
'user_id' => 'required',
'name' => 'nullable',
'description' => 'nullable',
'price' => 'nullable'
]);
// check if currently authenticated user is the owner of the listing
if (auth::user()->id !== $product->user_id) {
return response()->json(['error' => 'You can only edit your own products.'], 403);
}
$product->update($request->only(['name', 'description', 'price']));
return new ProductResource($product);
}
With this code, Laravel automatically returns a 404 Not found view but I would like it to be a JSON response instead.
Any elegant solution to accomplish this?
You can try to modify app/Exceptions/Handler.php file with something like that:
// add this before the class declaration
use Illuminate\Database\Eloquent\ModelNotFoundException;
//....
// modify the render() function as follows
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
return response()->json(['message' => 'Not Found'], 404);
}
return parent::render($request, $exception);
}
Let me know if it works I didn't have the time to try the code.
In the recent Laravel version (9) you can solve this by putting the below code inside the register function in app/Exceptions/Handler.php
$this->renderable(function (NotFoundHttpException $exception) {
return response()->json([
'status' => false,
'message' => 'Your message here',
], 404);
});
Ensure to import the namespace of NotFoundHttpException.
If your own error is ModelNotFoundException then do it this way
$this->renderable(function (ModelNotFoundException $exception) {
return response()->json([
'status' => false,
'message' => 'Your message here',
], 404);
});
This is my function :
public function index(Request $request)
{
$data = User::all();
return view('data.index',[
'data' => $data
]);
}
I write a test for this
public function testIndex()
{
$response = $this->call('GET', '/data');
$this->assertEquals(200, $response->status());
}
but not works. Show redirection
Response status code [302] is not a successful status code.
Failed asserting that false is true.
Here is my route:
Route::group(['prefix' => 'data'], function() {
Route::get('/', ['as' => 'data.index', 'uses' => 'DataController#index']);
});
I tried everything but still showing the same thing.
You just need to change your index() method as following :
public function index(Request $request)
{
$data = User::all();
return view('data.index',[
'data' => $data
])->setStatusCode(200);
}
Hope it will helps you. Thanks
When I used the passport package , I encountered this error
Call to a member function createToken() on null
Why do I get this error?
This is my code :
$users = Users::where('Email' , $username)
->where( 'Password' , $password)
->where('UserStatus' , config('global.active'))
->first();
if($users) {
$success['token'] = $users->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
} else {
return response()->json(['error'=>'Unauthorised'], 401);
}
$user = Auth::user(); is unnecessary and is what is causing your error.
$user = Users::where('Email' , $username)->where( 'Password' , $password)->where('UserStatus' , config('global.active'))->first();
if($user){
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}else{
return response()->json(['error'=>'Unauthorised'], 401);
}
If $users were null, there's no way that part of the control structure where createToken is getting called would be reached. I wonder if this is a red herring, and there's some middleware at work here. There are actually three instances of a method by that same name, and the namespace in your error message is notable absent there:
/vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php
/vendor/laravel/passport/src/ApiTokenCookieFactory.php
/vendor/laravel/passport/src/HasApiTokens.php
That last one is a trait being used by the User model, and is the one you're calling. But I'm wondering if that error is actually coming from one of the other two. Check your error-log, probably in /storage/logs/laravel.log, and see if there's a stack-trace that might lend a clue.
You can do other way around to make it work.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
public function authenticate(Request $request)
{
// add UserStatus logic here if any
if(Auth::attempt(['Email' => $request->username, 'Password' => $request->password], $request->remember))
{
$user = Auth::user();
$success['token'] = $request->user()->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
return response()->json(['error'=>'Unauthorised'], 401);
}