I think what I want is quite basic, I just can't find the proper syntax as I am still learning Laravel.
So, I am using google verification for sign ins on my website. This entails a post request to my backend that has to be handled, I have put this logic in a controller. My routes.php:
Route::post('google' , [
'as' => 'verify.index',
'uses' => 'verify#verifyIdToken'
]);
My controller (verify.php):
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class verify extends Controller
{
public function verifyIdToken($token)
{
$token = $_POST['id'];
$email = $_POST['email'];
return $this->getAuth()->verifyIdToken($token);
echo $this->getAuth()->verifyIdToken($token);
return view('aviewII')->with(['verify' => json_encode(verifyIdToken($token)),'email'=> json_encode($email)]);
}
}
Of course, because of how the function in the controller is written, I get the following error Missing argument 1 for App\Http\Controllers\verify::verifyIdToken() My question is, how do I tell the function in the controller to take $_POST['id'] as the argument for $token?
Something like this:
Route::post('google' , [
'as' => 'verify.index',
'uses' => 'verify#verifyIdToken ~with $_POST['id'] as $token'
]);
For additional reference, my actual post request looks like this:
$.post( "http://example.com/google", {email:profile.getEmail(),id:id_token} );
Controller method:
public function verifyIdToken(Request $request)
{
// Not necessary but a better practice for ajax 'POST' responses.
if($request->ajax() && $request->isMethod('post'))
{
return $request::get('token');
}
}
Route:
Route::post('google', ['as' => 'some.alias', 'uses' => 'SomeController#verifyIdToken']);
You are looking for Laravel's request class. You should type-hint the class on your method, which then allows loads of options to actually obtain the data. Something like:
use Illuminate\Http\Request;
public function verifyIdToken(Request $request)
{
$token = $request->input('id');
$email = $request->input('email');
return $this->getAuth()->verifyIdToken($token);
echo $this->getAuth()->verifyIdToken($token);
return view('aviewII')->with(['verify' => json_encode(verifyIdToken($token)),'email'=> json_encode($email)]);
}
The documentation on it has tons more useful information.
Related
In my Laravel 5.8 app I have many API routes which return paginated results. If I make a request to my API appending the following query string I can disable pagination.
http://api.test/users/?no_paginate=1
My question is... how can I disable no_paginate from being used on certain routes? I'd preferbly want some validation to go in the request class but I can't find anything in the docs for that.
You can do this using a Global Middleware.
Create a DisableNoPaginate Middleware:
php artisan make:middleware DisableNoPaginate
Then define what the middleware should do (DisableNoPaginate.php):
<?php
namespace App\Http\Middleware;
use Closure;
class DisableNoPaginate
{
public function handle($request, Closure $next)
{
//remove no_paginate param from request object
unset($request['no_paginate']);
return $next($request);
}
}
Arrange for the middleware to run on all routes (routes.php):
$app->middleware([
App\Http\Middleware\DisableNoPaginate::class
]);
Now the no_paginate query param should be stripped from all your incoming requests.
For the best approach to get users either paginate or get all listing by below code in UsersController
public function index($type = null, Request $request)
{
$builder = User::where(/*query*/);
if($type == "paginate") {
$items = $builder->paginate(10);
} else {
$items = $builder->get();
}
return view("users.index", ['users' => $items]);
}
Here is the route in web.php/api.php file
Route::get('/{type?}', ['as' => 'users.index', 'uses' => 'UsersController#index']);
Here url will be
http://api.test/users/paginate // get pagination response.
http://api.test/users // get response without pagination
I think this will help you.
I am getting 404 while am trying to access my api url here is my route :
MY Api route list:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/', function (Request $request) {
return $request->user();
});
Route::get('testapi','ApiDoctorController#testapi');
and the controller function that is provide data response is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi(){
$data = [
'name' => 'HEllo',
'age' => '24',
'height' => '5.4'
]
return response()->json($data);
}
}
When i try to access it in post-man at http://mydomain/project/api/testapi
its showing 404 error i am new to laravel help me out please
[![POSTMAN RESPONSE][1]][1][1]: https://i.stack.imgur.com/1uV6Z.png
First of all your missing the semicolon on the end of your data array.
Is Route::get('testapi','ApiDoctorController#testapi'); in your routes/api.php?
If not you'll need to define it so.
In postman you're doing domain/project/api/testapi when it should be domain/api/testapi as that is what you have specified in your routes file unless your entire laravel install is in domain/project.
I have added the semi-colon for you and formatted the code. If you're testing via postman please ensure that CSRF is disabled in your App/Http/Kernel.php (Just comment it out for your testing) then place it back in when you've setup authentication.
Let me know if this helps!
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi()
{
$data = [
'name' => 'Hello',
'age' => '24',
'height' => '5.4'
];
return response()->json($data);
}
}
Thanks everyone i got it i just add public after my project directory and it work thanks to all of you for your valuable time
I have some problems with my controller in laravel 5.4
My routes.php:
Route::group(array('domain' => '{subdomain}.site.com','as'=>'www::','middleware'=>array('web','varnish')), function() {
Route::any('/material/{page?}/', [
'as' => 'www_material', 'uses' => 'www\MaterialController#index'
]);
});
My controller:
<?php namespace App\Http\Controllers\www;
use App\Http\Controllers\Controller;
use View;
use DB;
use Illuminate\Http\Request;
class MaterialController extends Controller {
public function index($subdomain, $page = 1, Request $request)
{
echo $subdomain;
echo $page;
//...some code
}
}
There is no problems with url www.site.com/material/2/:
submodain = www,
page = 2
But www.site.com/material/:
Type error: Too few arguments to function App\Http\Controllers\www\MaterialController::index(), 2 passed and exactly 3 expected
I cant understand why this happend, because default value of page is 1.
Can someone help me? I cant solve this problem alone.
Thank you.
Your problem is the order the arguments are in the index method.
As the Request object will always be present put that first followed by $subdomain and then $page
As stated on the php website above example #5:
Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.
public function index(Request $request, $subdomain, $page = 1)
{
echo $subdomain;
echo $page;
//...some code
}
Try to remove trailing slash next to {page?} mentioned below and rerun the code.
Route::any('/material/{page?}', [
'as' => 'www_material', 'uses' => 'www\MaterialController#index'
]);
When pressing my send button it's giving error like this-
Here is my routes web.php bellow-
Route::group(['prefix'=>'ajax', 'as'=>'ajax::'], function() {
Route::resource('message/send', 'MessageController#ajaxSendMessage')->name('message.new');
Route::delete('message/delete/{id}', 'MessageController#ajaxDeleteMessage')->name('message.delete');
});
Here is my controller MessageController.php bellow:
public function ajaxSendMessage(Request $request)
{
if ($request->ajax()) {
$rules = [
'message-data'=>'required',
'_id'=>'required'
];
$this->validate($request, $rules);
$body = $request->input('message-data');
$userId = $request->input('_id');
if ($message = Talk::sendMessageByUserId($userId, $body)) {
$html = view('ajax.newMessageHtml', compact('message'))->render();
return response()->json(['status'=>'success', 'html'=>$html], 200);
}
}
}
Resource routes should be named differently:
Route::prefix('ajax')->group(function () {
Route::resource('messages', 'MessageController', ['names' => [
'create' => 'message.new',
'destroy' => 'message.destroy',
]]);
});
Resource routes also point to a controller, instead of a specific method. In MessageController, you should add create and destroy methods.
More info at https://laravel.com/docs/5.4/controllers#restful-naming-resource-routes
You can't name a resource. Laravel by default name it, if you want to name all routes you must specify each one explicitly. It should be like this:
Route::group(['prefix'=>'ajax', 'as'=>'ajax::'], function() {
Route::get('message/send', 'MessageController#ajaxSendMessage')->name('message.new');
Route::delete('message/delete/{id}', 'MessageController#ajaxDeleteMessage')->name('message.delete');
});
Update
Another mistake of yours was trying to resource a single method. A Route::resource() is used to map all basic CRUD routes in Laravel by default. Therefore, you have to pass the base route and the class i.e:
<?php
Route::resource('message', 'MessageController');
Look at web.php line 28.
Whatever object you think has a name() method, hasn't been set, therefore you try and call a method on null.
Look before that line and see where it is (supposed to be) defined, and make sure it is set to what it should be!
So far all attempts to modify the routing methods have failed.
Been following some documentation on laravel restful controllers and have one set up to do basic editing and adding of items to a database. It was going well till I hit the snag on... well I'm not sure what precisely is triggering the problem, but basically, everything works till I hit submit on the form and then it's Game Over.
Normally I'd be able to diagnose this by checking to see if I'm using the right call, or made a spelling mistake or something. But this is a new request for me, so I can't quite debug where the problem is coming from.
This is the error those who know what to look for. In full here.
MethodNotAllowedHttpException in RouteCollection.php line 218:
My routes are pasted here.
A printout of the routes is here:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContactFormRequest;
use App\UserEdit;
use DB;
use App\Http\Requests;
class EditUserController extends Controller
{
public function index()
{
$array = UserEdit::all()->toArray();
return view('UserEntry', compact('array'));
}
public function create()
{
$id = UserEdit::find(715)->toArray();
return view('NewUser', compact('id'));
}
public function store(UserFormRequest $request)
{
//$user = new UserEdit([
// 'name'=>$request->get('First_Name'),
// 'email'=>$request->get('email'),
// 'username'=>$request->get('name')
//]);
//
//$user->save();
//return \Redirect::route('users')->with('message', 'Nice Work.');
}
public function show($id)
{
try {
$array = UserEdit::findorFail($id)->toArray();
return view('UserEdit')->with('array', $array);
} catch(\Exception $e) {
return \Redirect::route('users.index')
->withMessage('This user does not exist');
}
}
public function edit($id)
{
$user = UserEdit::findorFail($id);
return view('EditUser')->with('user',$user);
}
public function update($id, UserFormRequest $request)
{
$user = UserEdit::findorFail($id);
$user->update([
'name' => $request->get('name'),
'email' => $request->get('email')
]);
return \Redirect::route('users.edit', [$user->id])->with('message', 'Details Updated!');
}
public function destroy($id)
{
//
}
}
The Blade is here.
if you have a hard time finding the solution the easiest solution is using
Route::any('users/{user}', 'UserEntryController#update');
this allow you to access this action with any method type
OR
Route::match(array('get', 'put'), 'users/{user}', 'UserEntryController#update');
so you need 2 method which are
get -> view
put -> submit update
you can just indicate which method type you want to be accessible with in this action
i think you are using model in form.try this
{{ Form::open(['method' => 'put', 'route'=>['users.update', $user->id], 'class'=>'form']) }}
As per your route list and route put doesnt taking id so you get method not found exception
PUT users/{user} App\Http\Controllers\EditUserController#update
instead of using resouce just type each route for each method
Route::put('users/{user}', 'EditUserController #update');
It seems like after sorting out the routes, the issue fell to a bad capitalisation. $user->id should have been $user->ID.