I am testing an API in Laravel 5.4. I am now in the part of storing a record via API. I am having some issues on how to use Request::input() or Input::get() to validate POST data.
LessonsController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Lesson;
use App\Acme\Transformers\LessonTransformer;
//use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
class LessonsController extends ApiController
{
/**
* #var Acme\Transformers\LessonTransformer
*/
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
// $this->middleware('sentry.auth')->only('post'); // basic level of protection for creating a lession
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
* If we are using basic authentication, we should be using SSL
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
if( ! Input::get('title') || ! Input::get('body')){
return $this->setStatusCode(422)->respondWithError('Parameters failed validation for a lesson.');
}
Lesson::create($request->all());
return $this->respondCreated('Lesson successfully created.');
}
/**
* Display the specified resource.
*
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$lesson = Lesson::find($id);
if( ! $lesson) {
return $this->respondNotFound('Lesson does not exist');
}
return $this->respond([
'data' => $this->lessonTransformer->transform($lesson)
]);
}
}
When I test my code above with POSTMAN using POST request. I am prompted with "{"error":"Parameters failed validation for a lesson.","status_code":422}"
.
I receive an error when I try to add data or I don't add data.
Do you have any idea how to correct my store() code? Any help is appreciated.
To validate form data in Laravel simply use "Laravel Form Requests". This allows you to validate your form data in request using some predefined validation rules of Laravel and if you need you can also create you custom laravel validation logic.
According to Laravel docs:
Form requests are custom request classes that contain validation logic.
It will simplify your validation logic, make your code neat and let you handle complex validations.
Try this, might help
public function store(Request $request)
{
if( ! $request->has('title') || ! $request->has('body')){
return $this->setStatusCode(422)->respondWithError('Parameters failed validation for a lesson.');
}
Lesson::create($request->all());
return $this->respondCreated('Lesson successfully created.');
}
The problem with my code above is that it does not have the $request var in the store() method.
In my code be below, the Request class is now injected into store method.
public function store(Request $request)
{
if (! $request->input('title') or ! $request->input('body') )
{
return $this->respondUnprocessableEntity('Parameters failed validation for a lesson.');
}
Lesson::create($request->all());
return $this->respondCreated('Lesson successfully created.');
}
Note: In postman, select x-www-form-urlencoded in Body
Related
I was trying to expand the extension which offers to see linked accounts for each user on the forum. It works in memberlist_view page and I would like to have it inside viewtopic_body.
I have a difficulty with narrowing the linked accounts to particular post id and author.
The closest I got is to have linked accounts from each user within the topic.
/** * Assign functions defined in this class to event listeners in the core * * #return array */ static public function getSubscribedEvents(): array { return array( 'core.viewtopic_modify_post_row' => 'viewtopic_linked_accounts_list',
` /**
* Show list of linked accounts in every post.
*
* #param data $event The event object
*
* #return void
*/
public function viewtopic_linked_accounts_list(data $event): void
{
// $this->template->assign_var('U_CAN_VIEW_LINKED_ACCOUNTS', $this->auth->acl_get('u_view_other_users_linked_accounts'));
foreach ($this->linking_service->get_linked_accounts($event['row']['user_id']) as $account)
{
$this->template->assign_block_vars('linked_accounts', array(
'ID' => $account['user_id'],
'USERNAME' => get_username_string('full', $account['user_id'], $account['username'], $account['user_colour']),
));
}
}`
I am trying to upload a Map/reduce type script to netsuite following a suitescript 2.0 training guide. I am receiving the following error: "SuiteScript 2.0 entry point scripts must implement one script type function."
I'm using the getInputData() and map() functions. Returning a reference object pointing to a saved search. Then extracting and logging the context value and the parsed context value (comparing json strings and js objects in the lesson).
Anyone see a syntax error, know what I might be missing, or what I can test for?
Code:
/**
* #NApiVersion 2.x
* #NScriptType MapReduceScript
*/
define(['N/search']),
function(search) {
function getInputData() {
return { type: 'search', id: 'customsearch_iii_payments' };
}
function map(context) {
var jsonResult = context.value
var searchResult = JSON.parse(context.value);
log.debug('JSON result' + jsonResult);
log.debug('Search Result' + searchResult);
}
return {
getInputData: getInputData,
map: map
}
}
It was a netsuite specific syntax error my linter didn't catch. My script definition wasn't wrapping the entire script, just the module declarations.
Working Code:
/**
* #NApiVersion 2.x
* #NScriptType MapReduceScript
* #NModuleScope SameAccount
*/
define(['N/search'],
function(search) {
function getInputData() {
return { type: 'search', id: 'customsearch_iii_payments' };
}
function map(context) {
var jsonResult = context.value
var searchResult = JSON.parse(context.value);
log.debug('JSON result' + jsonResult);
log.debug('Search Result' + searchResult);
}
return {
getInputData: getInputData,
map: map
}
});
Also check the #NScriptType notation, in case you have ScheduleScript, netsuite will expect you to have a function called ¨execute¨ on the return object no matter if the syntax is correct.
I found the issue for me was that my script referenced local files which I hadn't yet uploaded.
Upload other local files before creating a script record.
double check for the require vs define keyword in the main method definition. 2.X ScheduledScript use define
I created an application with ionic with the help of this tutorial: http://masteringionic.com/blog/2016-12-15-using-php-and-mysql-with-ionic/ a school programm
But when i want to select all my client, i get this error :
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttp…, text
My PHP script :
<?php
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'equida';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
$data = array();
// Attempt to query database table and retrieve data
try {
$stmt = $pdo->query('SELECT * FROM client');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
My javascript :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'page-lst-client',
templateUrl: 'lst-client.html'
})
export class LstClientPage {
/**
* #name items
* #type {Array}
* #public
* #description Used to store returned PHP data
*/
public items : Array<any> = [];
constructor(public navCtrl: NavController,
public http : HttpClient)
{
}
/*
* Triggered when template view is about to be entered
* Returns and parses the PHP data through the load() method
*
* #public
* #method ionViewWillEnter
* #return {None}
*/
ionViewWillEnter() : void
{
this.load();
}
/*
* Retrieve the JSON encoded data from the remote server
* Using Angular's Http class and an Observable - then
* assign this to the items array for rendering to the HTML template
*
* #public
* #method load
* #return {None}
*/
load() : void
{
this.http
.get('wequida/retrieve-client.php')
.subscribe((data : any) =>
{
console.dir(data);
this.items = data;
},
(error : any) =>
{
console.dir(error);
});
}
/*
* Allow navigation to the AddTechnologyPage for creating a new entry
*
* #public
* #method addEntry
* #return {None}
*/
addEntry() : void
{
this.navCtrl.push('AddClientPage');
}
/*
* Allow navigation to the AddTechnologyPage for amending an existing entry
* (We supply the actual record to be amended, as this method's parameter,
* to the AddTechnologyPage
*
* #public
* #method viewEntry
* #param param {any} Navigation data to send to the next page
* #return {None}
*/
viewEntry(param : any) : void
{
this.navCtrl.push('AddClientPage', param);
}
}
Your getting an HTML response from your PHP script.
You should include a json header in your PHP script.
header('Content-type: application/json');
The line
echo $e->getMessage();
will not output JSON. Your javascript does not accommodate sending errors.
In your PHP script you can use use:
echo json_encode(array('error' => false, 'data' => $data));
...
echo json_encode(array('error' => $e->getMessage(), 'data' => []));
Then in your javascript:
.subscribe((result: any) =>
{
if (result.error)
{
// error handling code
}
else
{
console.dir(result.data);
this.items = result.data;
}
},
If there is an error connecting to the database your script will output an HTML message with an 'Uncaught PDOException'. You can wrap that in try/catch as well.
To know what the problem is you should look at what your PHP script is outputting.
To do that
open the developers console [Option + ⌘ + J (on macOS), or Shift +
CTRL + J (on Windows/Linux)],
go to the 'Network' tab,
reload the page,
look for your php script and click on it,
open the 'Response' tab.
You will see the raw HTML or JSON response from the PHP script.
Edit - after reading comments:
If in the Response tab you see the full unparsed content of the PHP file then the web server you are using is not parsing PHP. You might be trying to do this without a sever by opening an HTML file with the javascript above through the file system using file:///C:/something/whatever.html
This will not work for obvious reasons.
I have two tables a ''users'' and ''announcement'', which announcement table have 3 download file so I wanna add a function when a user download a file add user id to the download file?
Annoucements Table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAnnoucementsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('announcements', function (Blueprint $table) {
$table->increments('project_id')->unsigned();;
$table->integer('types_id')->unsigned();
$table->foreign('types_id')->references('id')->on('types')->onDelete('CASCADE')->onUpdate('CASCADE');
$table->string('project_name');
$table->string('extension');
$table->date('deadline');
$table->string('biddingdocuments');
$table->string('amendmentdocuments');
$table->string('noticestenders');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('announcements');
}
}
Users Table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('securityq');
$table->string('securitya');
$table->string('name');
$table->string('fname');
$table->string('lname');
$table->string('gender');
$table->string('cname');
$table->integer('lnumber')->unique();
$table->string('province');
$table->string('city');
$table->string('pnumber');
$table->text('address');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
userAnnoucement controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Announcements;
class UserAnnoucment extends Controller
{
public function index(Request $request)
{
$announcements = Announcements::orderBy('project_id','DESC')->paginate(5);
return view('userAnnoucements.index',compact('announcements'))->with('i',
($request->input('page', 1) - 1) * 5);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function count(){
$announcements = new Announcements;
$announcements->extension = Auth::user()->id;
$announcements->save();
return $announcements;
}
}
``
No problem if the site is not overly busy. Otherwise you can have conflicts if there a simultaneous download.
If there is little to no traffic, programmatically copy the download file to a temporary folder, prepend the UserID to the filename and then download from there, ie: 1024_file.pdf. If the user breaks the download or returns then the file is already there, although you may want to clear the file after each download to conserve disk space, and use the same download code each time.
On a busier service, create a folder for each user logs on (if one is not already available) and do your business in those folders.
i have 2 tables user and tn_user, table user is a table containing information to log in, i made it by tutorial from https://laravel.com/ so basically it was automatically created, while tn_user is a table that i make by myself
USER TABLE
in case u can't see the atribut are id, name, email, password that the important things, email and password in this table is used to logging in
TN_USER TABLE
the atribut are cn_id, cv_name, cv_email, cn_phone, cv_position, cv_address, cv_country, cv_username, cv_password, cv_privileges, those are the important thing
based on the form below i want to insert username and password into table user and the rest into table tn_user and how do i do that? im pretty new to laravel so not really quite understand how, usually i use CI
UserController.php
this is where the code i use to insert data
i use json response to parse the data and not quite sure how to insert data into 2 tables little help here
public function createOrEdit(){
//get current user
$currentUserId = Auth::user()->id;
$isUpdate = false;
$id = Input::get('id');
$user = new UserCompany;
if($id != ""){
$user = UserCompany::where('cn_id', '=', $id)->firstOrFail();
$user->cv_updated_by = $currentUserId;
$user->cv_updated_at = Carbon::now();
$isUpdate = true;
}else{
$user->cv_created_by = $currentUserId;
$user->cv_created_at = Carbon::now();
}
$user->cv_name = Input::get('name');
$user->cv_position = Input::get('position');
$user->cv_email = Input::get('email');
$user->cn_phone = Input::get('phone');
$user->cv_address = Input::get('address');
$user->cv_username = Input::get('username');
$user->cv_password = Input::get('password');
$user->cv_country = Input::get('country');
if($isUpdate){
UserCompany::where('cn_id','=',$id)->update(['cv_updated_by' => $user->cv_updated_by,
'cv_updated_at' => $user->cv_updated_at,
'cv_name' => $user->cv_name,
'cv_position' => $user->cv_position,
'cv_email' => $user->cv_email,
'cn_phone' => $user->cn_phone,
'cv_country' => $user->cv_country,
'cv_username' => $user->cv_username,
'cv_password' => $user->cv_password,
'cv_address' => $user->cv_address]);
}else{
$user->save();
}
$returnedData = UserCompany::all();
$response = array(
'content' => $returnedData,
'status' => 'success',
);
return Response::json($response);
}
UserCompany.php is my model but since im new im not really understand how to use relationship yet
<?php namespace Activity;
use Illuminate\Database\Eloquent\Model;
class UserCompany extends Model {
protected $table = 'tn_user';
public $timestamps = false;
protected $fillable = [
];
/*public function usercompany(){
return $this->belongsTo('Activity\user');
}*/
}
You should know that in the UserCompany class, by setting the fillable, It means you are setting table column which you want to alter, in this case tn_user table. So this means, by setting
protected $fillable = [];
It means, that you are making no table columns should undergo modification when you are using commands like;
$user_details->cv_name = Input::get('cv_name');
Okay, so the first thing that you should know is that when creating two tables i.e users and tn_users you should have a column which carries a value which relate the two tables, I suggest that you are to user id from the users table:
I have noticed that you have used cn_id to be a linker, but it is best if every table has its own incrementing id column and also in this case, its own link_id column
Let's say you are starting over:
Open the command prompt or Terminal and go to you laravel project folder directory and type: -$ php artisan make:model User -m and again -$ php artisan make:model UserDetail -m
What this will do is, create User and UserDetail, and adding the -m means its creating the migrations for the models associated which is create_users_table and create_user_details_table
From the create_users_table simply create the desired table columns as shown below:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table){
$table->increments('id');
$table->integer('auth');
$table->string('username')->unique();
$table->string('email');
$table->string('password');
$table->boolean('online');
$table->string('lang', 2);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::drop('users');
}
}
Now for the create_tn_users_table its kinda important, you should set which links with the users account so that suppose you delete the users, his credentials are also removed, but you can make it do otherwise if you want.
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTnUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tn_users', function (Blueprint $table) {
$table->increments('id');
$table->string('full_name');
$table->string('username')->unique();
$table->integer('link_user_id')
->references('id')->on('users'); // Relationship btn table tn_users and users
$table->string('phone');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('tn_users');
}
}
Now go the command prompt or terminal and type -$ php artisan migrate to have the tables created.
Again on the command prompt or terminal type -$ php artisan make:controller UserController --resource and have the controller made together with its resources.
On the create() function inside the UserController, add the Request in as a parameter.
The functions is to be reached upon the submission of the form that you have created
namespace App\Http\Controllers;
use App\User;
use App\TnUser;
use ...
class UserController extends Controller{
public function create(Request $request){
$tn_user = new TnUser();
$user = new User();
$user->username = $request['username'];
$user->password = bcrypt($request['username']);
...
$user->save();
$tn_user->full_name = ucword(strtolower($request['full_name'));
$tn_user->link_user_id = $user->id; // uses the previously save id
$tn_user->phone = trim($request['phone']);
$th_user->save();
}
}
I hope I have answered you questions. Here are some helpful links to learn.
https://laravel.com/docs/5.1/migrations#creating-columns
https://laravel.com/docs/5.1/requests
You Create 2 objects
$user = new User()
$user->username = INPUT::get('username');
$user->password = $password // Hashed
$user->save();
$user_detail = new UserCompany() // Your detail table modal.
$user_detail->cv_name = Input::get('cv_name');
//etc
$user_detail->save()