Vuejs Laravel Axios create request - laravel

I have a vuejs method which implements axios to send a put/create request over to my laravel api create method passing over some data.
create(data) {
this.mute = true;
window.axios.put('/api/showreels/create', {data}).then(({ data }) => {
this.showreels.push(new Showreel(data));
this.mute = false;
}).catch(error => {
document.write(error.response.data);
});
},
My api.php is setup with the following resource
//Showreel
Route::resource('/showreels' , 'ShowreelController' , [
'except' => ['edit', 'show', 'store']
]);
And I have a create method to handle the request and update persist the data. (Which I have added a load of debugging in)
/**
* Create a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$message = 'sdfsdfsdf';
$message = $message . $request->heading . 'BALLS';
\App::abort(500, $message);
$showreel = new Showreel();
$showreel->heading = $request->heading;
$showreel->subheading = $request->subheading;
$showreel->detail = $request->heading;
$showreel->youtubeid = $request->youtubeid;
$showreel->heading = "test";
$showreel->subheading = "test";
$showreel->detail = "test";
$showreel->youtubeid = "test";
$showreel->save();
return response($showreel->jsonSerialize(), Response::HTTP_CREATED);
}
However laravel is giving me this error.
Not sure why I am getting this error?

Looks like I had the STORE option disabled in my api.php which was closing down the post request option. The post request now takes me through to my store method in laravel.

Related

post method on two actions within same controller in laravel

Following is my route file i.e web.php
Route::post('finddomainname','DomainController#finddomainname')->name('finddomainname');
Route::post('registerdomains','DomainController#registerdomains')->name('registerdomains');
Following is the code on my DomainController for both the actions used,
public function finddomainname(Request $request)
{
$this->validate($request,
['searchdomaintxt'=>'required',
'searchdomainext'=>'required']);
$searchdomaintxt = $request->input('searchdomaintxt');
$searchdomainext = $request->input('searchdomainext');
$domainname="";
if($searchdomaintxt && $searchdomainext)
{
foreach($searchdomainext as $ext)
{
$domainname.=$searchdomaintxt.".".$ext.",";
}
//dd($domainnames);
$domainnames= rtrim($domainname,',');
$response=$this->soap->multidomainsearch($domainnames);
$result=$response['RESPONSE']['DOMAINSEARCH'];
//dd($result);
if($result){
//return redirect()->action('searchresults', array('response' => $result));
return view('domain.searchresults',['response'=>$result]);
}
else
{
return view('domain.searchresults',['response'=>'']);
}
}
}
Following is the second action on which control come after submitting data
public function registerdomains(registerDomainsValidation $request)
{
$domains=$request->input('selecteddomains');
$selectedyear =$request->input('selectedyear');
$domaincontactid=\Session::get('domaincontactid');
$alldomains='';
foreach($domains as $domain)
{
$alldomains.=$domain.",";
}
$alldomains=rtrim($alldomains,',');
$response=$this->soap->registerdomains($alldomains,$domaincontactid,$selectedyear);
return view('domain.searchresults',['response'=>$response]);
}
but when i submit data it will show me this error
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
You are trying to access your POST route using a GET request, that's why you are receiving a MethodNotAllowedHttpException. To solve this issue, make sure that your <form></form> tag contains the appropriate method attribute.
<form action="{{ YOUR_URL }}" method="POST">
...
</form>
Or if you want to perform the request inside your controller, you can use Guzzle to send http requests. In your controller you can do:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('POST', 'YOUR_URL', [
'form_params' => [
'foo' => 'bar'
]
]);

AngularJS 2.0 http.post returns 500 (Internal server error)

I'm trying to use angular 2.0 to add a new hero via my PHP Laravel API and I always get 500 Internal server error response.
My API (laravel): Create a new hero route:
Route::group(array('prefix' => 'api/v1', 'middleware' => ['web']), function()
{
//Add a new hero
Route::post('/heroes/create', 'HeroController#store');
});
HeroController#store method: (Tested and works with a Laravel form)
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$hero = new Hero;
$hero->name = $request->name;
$hero->description = $request->description;
$hero->avatar = "None";
$hero->save();
$heroes = Hero::paginate(5);
return view('/heroes/index', [
'heroes' => $heroes
]);
}
Angular onSubmit() Method: (trying to make it work without a form..)
onSubmit(value: string): void {
let headers = new Headers();
headers.append('Content-type', 'application/x-www-form-urlencoded');
let formPayload = new URLSearchParams();
formPayload.set('name', name.value);
formPayload.set('description', desc.value);
formPayload.set('_token', _token.value);
this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes/create',
JSON.stringify({name:'Joe',description:'wonder', _token:'knUS8vUxihTj4YJhjVkqmRBJJkVDDCABIZaRwXhN'}),
{headers:headers})
.map((res: Response) => res.json())
.subscribe(
data => { this.heroes = data;
},
err => console.error(err),
() => console.log('done');
);
What I get:
POST http://127.0.0.1/heroWorld/public/api/v1/heroes/create 500 (Internal Server Error)
What's wrong? I'm trying to fix it for several days, nothing works.
You create a form data using the URLSearchParams class but you use another object in the post method. You could try the following instead:
let formPayload = new URLSearchParams();
formPayload.set('name', name.value);
formPayload.set('description', desc.value);
formPayload.set('_token', _token.value);
this.http.post('http://127.0.0.1/heroWorld/public/api/v1/heroes/create',
formPayload.toString(), // <------
{headers:headers})

how to get facebook email id from Nodge/yii2-eauth

Am trying to integrate Yii2 EAuth for facebook login integration.
I made configaration * in model am using below code
public static function findIdentity($id) {
if (Yii::$app->getSession()->has('user-'.$id)) {
return new self(Yii::$app->getSession()->get('user-'.$id));
}
else {
return isset(self::$users[$id]) ? new self(self::$users[$id]) : null;
}
}
/**
* #param \nodge\eauth\ServiceBase $service
* #return User
* #throws ErrorException
*/
public function findByEAuth($service) {
if (!$service->getIsAuthenticated()) {
throw new ErrorException('EAuth user should be authenticated before creating identity.');
}
$id = $service->getServiceName().'-'.$service->getId();
// echo $id;exit;
print_r($service->getAttribute('email'));
echo '<pre>';
print_r($service->getAttributes());
exit;
$attributes = array(
'id' => $id,
'username' => $service->getAttribute('name'),
'authKey' => md5(#$id),
'profile' => $service->getAttributes(),
);
$attributes['profile']['service'] = $service->getServiceName();
Yii::$app->getSession()->set('user-'.$id, $attributes);
return new self($attributes);
}
i want email , pls can any one help me to get facebook email id...thanks in advance......
I managed to get the email of the user from facebook after changing the few setting in vendor\nodge\yii2-eauth\src\services\FacebookOAuth2Service.php.
Edit FacebookOAuth2Service.php
Override protected $scopes = array(self::SCOPE_EMAIL);
And modify the fetchAttributes() functions. It should look like this:
protected function fetchAttributes()
{
$info = $this->makeSignedRequest('me');
$this->attributes['id'] = $info['id'];
$this->attributes['name'] = $info['name'];
$this->attributes['url'] = $info['link'];
$this->attributes['email'] = $info['email'];
return true;
}
Try and see it it works for you.

Phalcon: how to get controller and action name

I'm trying to build some authorization into my Phalcon-based app. In my bootstrap file I instantiate my Auth class (which extends Component), and run my authorize() function. Inside that function I get the dispatcher by calling $Dispatcher = $this->di->getShared('dispatcher').
That all seems to run fine. However, when I then call $Dispatcher->getControllerName(), it returns NULL.
How do I access the controller name?
Here is my bootstrap file:
$Debug = new \Phalcon\Debug();
$Debug->listen();
#try{
# Create a Dependency Injection container
$DI = new \Phalcon\DI\FactoryDefault();
# Load config
$Config = require '../app/config/config.php';
$DI->setShared('config',$Config);
# Register an autoloader
$Loader = new \Phalcon\Loader();
$Loader->registerDirs($Config->phalcon->load_dirs->toArray());
$Loader->registerNamespaces($Config->phalcon->namespaces->toArray());
$Loader->register();
# Initialize Session
$Session = new \Phalcon\Session\Adapter\Files();
$Session->start();
$DI->setShared('session',$Session);
# Set up the View component
$DI->set('view',function() use($Config){
$View = new \Phalcon\Mvc\View();
$View->setViewsDir($Config->dir->views_dir);
$View->registerEngines(['.phtml'=> function($View,$DI) use ($Config){
$Volt = new \Phalcon\Mvc\View\Engine\Volt($View,$DI);
$Volt->setOptions([ 'compiledPath' => $Config->dir->views_compile_dir,
'compileAlways' => $Config->app->views_compile_always
]);
return $Volt;
}
]);
$View->Config = $Config;
return $View;
});
# Check authorization
$Auth = new Auth($DI);
if($Auth->authorize()){
$DI->setShared('user',$Auth->getUser());
}
else{
$DI->get('view')->render('system','notallowed');
exit();
}
# Set up connection to database
$DI->set('db',function() use($Config){
return new \Phalcon\DB\Adapter\Pdo\Mysql([ 'host' => $Config->database->host,
'dbname' => $Config->database->database,
'username' => $Config->database->username,
'password' => $Config->database->password
]);
});
# Set up base URL
$DI->set('url',function() use($Config){
$URL = new \Phalcon\Mvc\Url();
$URL->setBaseUri('/'.basename($Config->dir->app_dir_web));
return $URL;
});
# Set up message flashing to use session instead of direct
$DI->set('flash',function(){
return new \Phalcon\Flash\Session();
});
# Handle the requested URL
$App = new \Phalcon\Mvc\Application($DI);
# Echo the output
echo $App->handle()->getContent();
/*
}
catch(\Phalcon\Exception $e){
echo 'Phalcon Exception: ',$e->getMessage();
}
*/
I think that untill you call $app->handle() the dispatcher won't be properly setup.
Maybe not a direct response, but I've manage to successfully implement authorization using Vokuro app as a example: https://github.com/phalcon/vokuro.
Your bootstrap looks ok should work.
I'm using this in bootstrap file :
/**
* Handle the request
*/
$application = new \Phalcon\Mvc\Application();
$application->setDI($di);
if (!empty($_SERVER['REQUEST_URI'])) {
$uriParts = explode('?', $_SERVER['REQUEST_URI']);
$uri = $uriParts[0];
} else {
$uri = '/';
}
echo $application->handle($uri)->getContent();
As you can see there is $uri parameter passed to $application->handle() function.
Inside controllers: $this->dispatcher->getControllerName() works fine.
I am using a Router object so the following works for me before the ->handle call
/** #var $router \Phalcon\Mvc\Router */
$router = require APPLICATION_PATH.'/routes/default.php';
$router->handle($url);
$router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI);
/** #var $matched \Phalcon\Mvc\Router\Route */
$matched = $router->getMatchedRoute();
$paths = $matched->getPaths();
echo 'controller : ',$paths['controller'],"<br />";
echo 'action : ',$paths['action'],"<br />";
This is an old thread but in case people still need it, I will show you two ways to properly handle authorization.
In both cases, you should check authorization in a "before middleware", not anywhere else.
Checking authorization directly in your front controller is a bit premature.
1. By retrieving the handler, as you asked
Here you perform authorization checks only if needed. It is a bit more code, but a bit more effective too because you don't have to even use the database if you don't need to.
$app = \Phalcon\Mvc\Micro;
$app->before(function() use ($app)
{
/**
* #var \Phalcon\Mvc\Controller $oHandler
*/
$oHandler = null;
$sAction = null;
$aHandlerArr = (array)$app->getActiveHandler();
if (!empty($aHandlerArr) && !empty($aHandlerArr[1]))
{
$oHandler = $aHandlerArr[0];
$sAction = $aHandlerArr[1];
}
if ($oHandler && $oHandler->isAuthRequired($sAction))
{
// Do auth, and send an error if failed
}
});
2. Without voodoo magic
The other way is to simply try authorization in your before middleware without checking if you need it. It is the same code as above, but without the handler retrieval.
$app = \Phalcon\Mvc\Micro;
$app->before(function() use ($app)
{
// Do auth ...
// Set member in your app, if auth succeeded.
// Then in your controller actions, simply check for the member in your app
});
XD
$this->router->getActionName()

how to get user profile from linked in using codeigniter

How do you get the user profile after you have finish verification in linkedin? I've been googling around and found some tutorials but none of them are working, or should I say I can't get them to work. Below is my controller.
function __construct(){
parent::__construct();
$this->config->load('linkedin');
$this->data['consumer_key'] = $this->config->item('api_key');
$this->data['consumer_secret'] = $this->config->item('secret_key');
$this->data['callback_url'] = site_url() . 'main/linkedin_display';
}
function linkedin_request(){
$this->load->library('linkedin', $this -> data);
$token = $this->linkedin->get_request_token();
$oauth_data = array(
'oauth_request_token' => $token['oauth_token'],
'oauth_request_token_secret' => $token['oauth_token_secret']
);
$this->session->set_userdata($oauth_data);
$request_link = $this->linkedin->get_authorize_URL($token);
header("Location: " . $request_link);
}
function linkedin_display{
// get user details(first name, email etc) here
}
Add the following function to your linkedin library, in order to get data
function getData($url, $access_token)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $access_token, "GET", $url);
$request->sign_request($this->method, $this->consumer, $access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($shareUrl, $auth_header, "GET");
return $response;
}
Then create a function in your controller as follows:
/**
* Fetch linkedin profile
*/
function myprofile()
{
$auth_data = $this->session->userdata('auth');
$this->load->library('linkedin', $this->data);
$status_response = $this->linkedin->getData('http://api.linkedin.com/v1/people/~', unserialize($auth_data['linked_in']));
print_r($status_response);
}
This should work for you.

Resources