I developed an API and I have a problem with this page I add it in my route and always I get a 404 error I don't know why
this my controller:
class InsertPPictureController extends Controller
{
public function profilepicture (Request $request)
{
$input = $request->all();
$validator = Validator::make($input, [
'id_user'=> 'required',
'picture'=> 'image|nullable|max:1999'
] );
$user = User::findOrFail($request->id);
$user_id = $request->id ;
if($request->hasFile('picture')){
// Get filename with the extension
$filenameWithExt = $request->file('picture')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('picture')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $user_id.'.'.$extension;
// Upload Image
$path = $request->file('picture')->storeAs('public/profilepic', $fileNameToStore);
$user->pic_path = $fileNameToStore ;
$user->update();
} else {
$fileNameToStore = 'noimage';
}
return response()->json(' Success : User updated with success ',200);
}
}
and this is my api.php
Route::group(['middleware' => ['jwt.verify']], function() {
Route::get('logout', 'AuthController#logout');
Route::post('postcreditscards', 'CreditsCardsController#stockcards');
Route::get('getcreditscards', 'CreditsCardsController#index');
Route::get('getmybalance', 'MyBalanceController#index');
Route::get('getuserdata', 'AuthController#getuser');
Route::post('sendMoneyTransaction', 'MyBalanceController#updatebalance');
Route::post('isvalidnumber', 'AuthController#validnumber');
Route::post('updateuser', 'AuthController#updateuser');
Route::post('insertprofilepicture','InsertPPictureController#profilepicture');
});
all the pages work fine only this page doesn't work
Route::post('insertprofilepicture','InsertPPictureController#profilepicture');
You are getting 404 error because of the following line in you controller code:
$user = User::findOrFail($request->id);
The id you are providing, does not exist in your users table and as you are not catching the exception hence Laravel is returning a 404 response, which is actually ModelNotFoundException
Reference here
Go to : "Not Found Exceptions" section of the above link. Here is some lines from doc:
If the exception is not caught, a 404 HTTP response is automatically sent back to the user
echo '<pre>'.print_r($user,1);die();
just put in this line after the
$user = User::findOrFail($request->id);
line. i suggest you to check the data array pass to this controller. if it is pass, after line by line you can check.
Related
I realize this question has been asked several times on this forum, but none of the solutions given has resolved my particular issue.
I get the above error when trying to update my DB.
Here is a snippet of my code
I have tried adding findorfail on my request by id
$service=Service::findorfail($request->input('id'));
This returns a 404 page.
ServiceController.php
public function updateService(Request $request){
// return $request->all();
$this->validate($request, ['serviceTitle'=> 'required',
'serviceSubTitle'=> 'required',
'description'=> 'required',
'slug' => 'required|min:3|max:255|unique:services',
'serviceImage'=>'image|nullable|max:1999']);
$service=Service::find($request->input('id'));
$service->title =$request->input('serviceTitle');
$service->sub_title =$request->input('serviceSubTitle');
$service->slug =$request->input('slug');
$service->description =$request->input('description');
if($request->hasFile('serviceImage')) {
//1 : get filename with ext
$fileNameWithExt = $request->file('serviceImage')->getClientOriginalName();
//2 : get just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//3 : get just extension
$extension = $request->file('serviceImage')->getClientOriginalExtension();
//4: filename to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload image
$path =$request->file('serviceImage')->storeAs('public/serviceImage', $fileNameToStore);
$old_image =Service::find($request->input('id'));
if($old_image!='noimage.jpg') {
Storage::delete('public/serviceImage/'.$old_image->image);
}
$service->image =$fileNameToStore;
}
$service->update();
return redirect('/services')->with('status', 'The '.$service->title.' Service has been updated successfully');
}
The error log tells me the error is on this specific line:
$service->title =$request->input('serviceTitle');
Thank you for time and assistance.
Currently I am working on a vue/laravel project where only authorized users should be allowed to call a route that uses domPDF to generate and download a PDF file. Unfortunately when I put the route inside Route::group(['middleware' => 'auth:api'], function(){...}) in api.php, I get the following error:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [login] not defined.
http://localhost:8000/api/qrsheets/1/download
This error only occurs for this specific route. The other routes with json-response inside this middleware function work fine, and when I access them I have an oAuth token inside my Authorization-header. I am using laravel's passport to have this token generated. What should be a simple and good solution for protecting this route?
api.php
use Illuminate\Http\Request;
Route::group(['middleware' => 'auth:api'], function(){
// QR SHEETS
Route::get('/qrsheets/{id}/download', 'QrSheetController#downloadPDF')->name('qrsheets.download');
});
QrSheetController.php -> downloadPDF
public function downloadPDF(Request $request){
// find sheet by id
$id = $request->route('id');
$sheet = QrSheet::find($id);
// set papaer width and height for pdf
$paperWidthPt = $sheet->page_width_mm * (72 / 25.4);
$paperHeightPt = $sheet->page_height_mm * (72 / 25.4);
// set dimensions as paperformat
$paperFormat = array(0,0,$paperWidthPt,$paperHeightPt);
// create and download pdf
$pdf = PDF::loadView('qrsheet.pdf-sheet', compact('sheet'))->setPaper($paperFormat, 'portrait');
$filename = $sheet->alias . ".pdf";
return $pdf->download($filename);
}
AuthController.php -> login - just in case you need to know how token is generated
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error' => 'Unauthorized']);
}
}
kind regards,
Tim
I have tried to send some values using post method in REST API Tool.
I have used Laravel version 5.4.
I have tried the following code
Route File:
Route::post('ws-register',array('uses' => 'AppController#doRegister'));
Controller File
public function doRegister() {
$rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|alpha_num|min:6|max:15'
);
$messages = array('alpha_spaces' => 'Name must be alphanumeric');
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails()) {
$error = $validator->errors()->all(':message');
$response['message'] = $error[0];
$response['code'] = false;
} else {
$user = new Users;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
$response['user_id'] = $user->id;
$response['message'] = "Success";
$response['code'] = true;
}
}
return Response::json($response);
}
While calling through REST API POST Method, I am getting "500: Internal Server Error" as response.
Can anyone help me out to find what I have done wrong?
Assuming you are having TokenMismatchException in VerifyCsrfToken.php error, as was written in question comments.
As stated in app/Http/Kernel.php, VerifyCsrfToken middleware is applied to all routes in routes/web.php. But it is not applied to routes/api.php
If you are making API request, may be it is better to place your route in routes/api.php file. Then, when making API call, make sure to add /api prefix to your request, like this:
POST http://example.app/api/ws-register
But if you still want to to keep your route in routes/web.php, think of adding CSRF-protection. More info at https://laravel.com/docs/5.4/csrf
I have a file full of logs! I called them apache.logs.
So now I need to get them in Laravel and I don't know how.
I just want to save all logs in a variable ($logs) and view them.
public function getlogs ()
{
$logs = \Request::file('apache.log');
return view('logs' , [
'all_logs' => $logs
]);
}
This doesn't work and I don't know what I need to change.
If your using \Request::file then the file should come along with the request params, But here seems like you want to access a stored file in file system using laravel
to do that
ini_set('memory_limit','256M');
$logs = \File::get('apache.log');
return view('logs' , [
'all_logs' => $logs
]);
UPDATE
if you file is in root same like composer.json then you need to change the path to match with it like
ini_set('memory_limit','256M');
$path = base_path()."/apache.log"; //get the apache.log file in root
$logs = \File::get($path);
return view('logs' , [
'all_logs' => $logs
]);
wrap this in a try catch block for best practice, because in some case if apache.log not exists or not accessible laravel trow a exception, we need to handle it
try {
ini_set('memory_limit','256M');
$path = base_path()."/apache.log"; //get the apache.log file in root
$logs = \File::get($path);
return view('logs' , [
'all_logs' => $logs
]);
} catch (Illuminate\Filesystem\FileNotFoundException $exception) {
// handle the exception
}
I am writing a logout function and simply after deleting all necessary information from database, I clear session and logout with a redirect. I would like to redirect the user to the home page (landing page) and this did work in another function which is the login (upon successful login, I would redirect to home. Here is how it is done in my code:
public function logout()
{
$userModel = new User;
$userToken = Session::get('userToken');
$isCleared = $userModel->clearSessionForUser($userToken);
if($isCleared == true)
{
Session::forget('userToken');
Session::flush();
return Redirect::route('/');
}else{
$errorArray = array('errorMsg'=>'logout operation didn't succeed ');
return View::make('errors.error', $errorArray);
}
}
the routes.php has the following route:
Route::get('/', 'MainController#index');
and I've done this before as I said with login and it worked but here it is saying:
InvalidArgumentException
Route [/] not defined.
Here is how the login part containing the redirect looks like:
$userModel = new User;
$isUser = $userModel->validateDetails($email, $password);
if($isUser==true)
{
return Redirect::route('/');
}else{
$errorArray = array('errorMsg'=>'The credentials doesn\'t match any user records or the account has not been activated ');
return View::make('errors.error', $errorArray);
}
Please support and let me know why it works once and not again although both are methods in the same class and targeting the same route.
The parameter in Redirect::route should be the route name. So, if you modified your routes file as such:
Route::get('/', array('as' => 'home', 'uses' => 'MainController#index'));
Then you can utilize that route name in Redirect::route:
return Redirect::route('home');
Alternatively, you can simply use Redirect::to, to redirect to a URL:
return Redirect::to('/'); // This is the URL
I dont know if it is related - but you have a syntax error:
$errorArray = array('errorMsg'=>'logout operation didn't succeed ');
should be
$errorArray = array('errorMsg'=>"logout operation didn't succeed ");
or
$errorArray = array('errorMsg'=>'logout operation didn\'t succeed ');