How to create POST service URL and save data to DB using Laravel 5? - api

i want to get some data from a mobile app using POST and save it on my laravel 5 application database.
mycontroller
public function postBookingDetails(Request $request)
{
$FodMaps = $request->only('name','fructose');
return $FodMaps;
}
Route::post('booking', 'FodMapController#postBookingDetails');
table Structre:
id (autoincrement)
name varchar
fructose varchar
Model
protected $table = 'food_directory';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'lactose', 'fructose','polyols','fructan'];

public function postBookingDetails(Request $request)
{
$FodMaps = $request->only('name','fructose');
$FoodDirectory = new FoodDirectory;
$FoodDirectory->name = $request->input('name');
$FoodDirectory->fructose = $request->input('fructose');
$FoodDirectory->save();
return $FoodDirectory;
}
also add to your model:
public $timestamps = false;
And ofcourse dont forget to add to the top of your controller:
use App\FoodDirectory;

Related

How to denote a Request Facade by a variable in Laravel?

I am doing some experiment to make my controllers as much dynamic as I can. Let me give you a brief overview. I have a controller Logo Controller which I have set up like this:
use App\Models\Logo;
class LogoController extends Controller
{
public function add(Request $request)
{
$data['entity'] = 'logo';
$newEntityObj = new Logo;
$newEntityObj->title = $title; // set title
$newEntityObj->type = $type; // set type
$saveNewEntityData = $newEntityObj->save(); // save the entity data
------------------
-------------------
}
}
Now I made some changes like:
using a variable to denote the Logo Model.
$modelClass = "App\\Models\\" . ucfirst($data['entity']);
And then, using the $modelClass variable to execution Eloquent actions on it, like this:-
$newEntityObj = new $modelClass;
$newEntityObj->title = $title; // set title
$newEntityObj->type = $type; // set type
$saveNewEntityData = $newEntityObj->save(); // save the entity data
So the Logo Controller Class has been updated to:
use App\Models\Logo;
class LogoController extends Controller
{
public function add(Request $request)
{
$data['entity'] = 'logo';
$modelClass = "App\\Models\\" . ucfirst($data['entity']);
$newEntityObj = new $modelClass;
$newEntityObj->title = $title; // set title
$newEntityObj->type = $type; // set type
$saveNewEntityData = $newEntityObj->save(); // save the entity data
------------------
-------------------
}
}
Now I have created a Validationb Request File to use it for form validation. I am using it like this:
// Request Validation Inclusion //
use App\Http\Requests\AdminRequests\LogoValidation\LogoRequest;
public function add(LogoRequest $request)
{
--------------------------
--------------------------
}
Now instead of writing public function add(LogoRequest $request) I want to make it more dynamic. Something like this:
class LogoController extends Controller
{
public static $classEntity = 'logo';
public static $classFormattedEntity = null;
public static $classRequestVariable = null;
public function __construct()
{
$entityArray = explode('-', str_replace('_', '-', self::$classEntity));
foreach($entityArray as $keyEntity => $rowEntity)
{
if($keyEntity !== 0)
$entityArray[$keyEntity] = ucfirst($rowEntity);
}
self::$classFormattedEntity = implode('', $entityArray);
self::$classRequestVariable = "App\\Http\\Requests\\AdminRequests\\" . ucfirst(self::$classFormattedEntity) . "Validation\\" . ucfirst(self::$classFormattedEntity) . "Request";
}
public function add(self::$classRequestVariable $request)
{
..............................
..............................
}
}
The variable self::$classRequestVariable actually prints App\Http\Requests\AdminRequests\LogoValidation\LogoRequest
But when I am writing public function add(self::$classRequestVariable $request) instead of public function add(LogoRequest $request) I am getting the following error:

JWTAuth always returns false in Laravel 6

I want to create a Laravel 6 backend with JWT authentication and when I want to sign in a user, JWTAuth always returns false, I google it but can't find any solution for it.
here are my project files codes,
this is my UserController
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use App\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
class UserController extends Controller
{
public function signup(Request $request)
{
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = $request->input('password');
$user->save();
return response()->json(['message'=>'User Created Successfully!',$user],201);
}
public function signin(Request $request)
{
$credentials = [];
$credentials['email'] = $request->input('email');
$credentials['password'] = bcrypt($request->input('password'));
try{
if(!$token = JWTAuth::attempt($credentials)){
return response()->json(['error'=>'Invalid Credentials!'],401);
}
}catch(JWTException $e){
return response()->json(['error' => 'Could Not Create Token!'],500);
}
return response()->json(['token'=>$token],200);
}
}
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier() {
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims() {
return [];
}
public function setPasswordAttribute($password)
{
if ( !empty($password) ) {
$this->attributes['password'] = bcrypt($password);
}
}
}
And Api Route
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('/user','UserController#signup');
Route::post('/user/signin','UserController#signin');
when I want to sign in a user, JWTAuth:attempt($credentials), I don't know what I am missing or wrong?
Is there any solution?

Symfony 4 API Rest PUT : Map data to database entity

I'm a begginer in Symfony 4 and I'm developing an API Rest. I want to create a PUT resource that can handle many update cases.
In my case, I have a user with many properties but I will take an example with 3 properties to keep things simple :
User {
username,
email,
password
}
My PUT resource can be called in order to update Username, update Email or update Password. For example, to update Username, the user of my API will send a PUT request with only username :
{
username: "New username"
}
Same for email and password, he will only send the property he wants to change.
My problem is in my Controller, I have to do things like this :
/**
* #Rest\Put("/user/{id}")
* #param Request $request
* #return View
*/
public function putUserRequest(Request $request)
{
$userId = $request->get('id');
$user = $this->doctrine->getRepository(User::class)->findOneBy('id' => $userId);
$userFromRequest = $this->serializer->deserialize($request->getContent(), User::class, 'json');
if ($userFromRequest->getUsername() != NULL) {
$user->setUsername($userFromRequest->getUsername())
}
if ($userFromRequest->getEmail() != NULL) {
$user->setEmail($userFromRequest->getEmail())
}
if ($userFromRequest->getPassword() != NULL) {
$user->setPassword($userFromRequest->getPassword())
}
// ...
}
In my example I have only 3 properties, but imagine when I have 30 properties.
With Symfony 3 I used forms to validate / save my datas :
$form->submit($request->request->all(), $clearMissing);
Where $clearMissing is false to keep datas not provided by the user of my API. I can't find a way to do it with serializer but I guess I'm doing things wrong.
Thanks.
If I understand correctly, You can use the validator Component like this :
/**
* #Rest\Put("/user/{id}")
* #param Request $request
* #return View
*/
public function putUserRequest(User $user, Request $request, ValidatorInterface $validator)
{
$data = $request->getContent();
$this->serializer->deserialize($data, User::class, 'json', ['object_to_populate' => $user]);
//At this moment, the data you sent is merged with your user entity
/** #var ConstraintViolationList $errors */
$errors = $validator->validate($user, null ,['groups' => 'user_update']);
if (count($errors) > 0) {
//return json reponse with formated errors;
}
//if ok $entityManager->flush() and Response Json with serialization group;
...
}
In your user class :
class User implements UserInterface
{
/**
* #Assert\Email(groups={"user_create", "user_update"})
*/
private $email;
/**
* #Assert\NotBlank(groups={"user_create", "user_update"})
* #Assert\Length(min=7, groups={"user_create", "user_update"})
*/
private $password;
/**
* #Assert\Length(min=2, groups={"user_create", "user_update"} )
*/
private $username;
}
Related Validator component documentation : https://symfony.com/doc/current/validation/groups.html
You can also check this project : https://github.com/attineos/relation-deserializer

Phalcon DB Criteria in Model ORM

In Phalcon model is there a way to use SQL "IN" condition and other database criteria? For example, i want to execute this query in phalcon
SELECT user_fullname, user_email FROM tbl_users WHERE user_id IN (1,2,3,4,5)
I know you can use query builder but I want it to be ORM. I want a method in my model getUsersByIds($userIds, $columnsToSelect) that will accept an array of userids and columns that you want to fetch in the table.
See my model below
<?php
use Phalcon\Mvc\Model;
class User extends Model
{
/**
*
* #var integer
*/
public $user_id;
/**
*
* #var string
*/
public $user_email;
/**
*
* #var string
*/
public user_phone;
/**
*
* #var string
*/
public user_fullname;
public function initialize()
{ $this->hasMany('user_id','Store\Bag','user_id');
}
public function getSource()
{
return "tbl_user";
}
public function find($parameters = null)
{
return parent::find($parameters);
}
public function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
/**
* I want to execute this query in my model
* SELECT user_fullname,user_email from tbl_user where user_id IN (1,2,3,4,5);
*/
public function getUsersByIds($ids=array(), $columns=array())
{
if(!is_array($ids))
$ids = array($ids);
if(!is_array($columns))
$columns = array($columns);
...................................
.........................
..............
}
}
There are two ways of doing this:
Method 1: inWhere('columnName', array('columnValues'))
public function getUsersByIds(array $userIds, $columnsToSelect = '') {
return self::query()
->inWhere('id', $userIds)
->columns($columnsToSelect ?: '*')
->execute();
}
This one goes in your User model
Method 2: conditions => 'id IN ({ids:array})
User::find(['id IN ({ids:array})',
'columns' => $columnsToSelect,
'bind' => array('ids' => $userIds)]);
I am typing on my mobile, so there might be a typo in there.

Edit profile page with 3 tables - Yii frameworks

I am new on Yii framework, so please i need some help where to start.
What i need is, action and module to display a form to a user, which his will be able to edit is own profile (with profile picture), so i have 3 table
user_account || user_personal || user_general
how can i build a form that insert and update those 3 table at once?
i try this:
This is what i did, but its still not saving the data even into 1 table.
public function actionUpdate() {
$model = new ProfileUpdate();
if(isset($_POST['ProfileUpdate']))
{
$model->attributes = $_POST['ProfileUpdate'];
if($model->validate())
{
$account = new Profile();
$account->userid = Yii::app()->user->id;
$account->name = $model->name;
$account->website = $model->website;
$account->category = $model->category;
$account->save();
$this->redirect('profile');
}
}
model:
class Profile extends CActiveRecord
{
public $userid;
public $name;
public $website;
public $category;
public static function model()
{
return parent::model(__CLASS__);
}
public function tableName()
{
return 'userinfo';
}
public function primaryKey()
{
return 'id';
}
public static function userExists($user)
{
return self::model()->countByAttributes( array('username'=>$user) ) > 0;
}
}
You can use all three models in a single function
for example:
In create function
$model_account = new user_account;
$model_personal= new user_personal;
$model_general = new user_general;
$this->render('create',array(
'model_account'=>$model_account, 'model_personal' => $model_personal, 'model_general' => $model_general
));
here the all three models pass by render to create page.
in form page you can use the every model attributes as fields
Like this
echo $form->textField($model_account,'account_name');
echo $form->textField($model_personal,'email');
echo $form->textField($model_general,'address');
In create function / Update function
$model_account->attributes = $_POST['user_account'];
$model_personal->attributes = $_POST['user_personal'];
$model_general->attributes = $_POST['user_general'];
if($model_account->validate() && $model_personal->validate() && $model_general->validate())
{
$model_account->save();
$model_personal->save();
$model_general->save();
}