I am new to laravel and I am facing following problem
My problem
Problem i m facing is that whenever I submit the form after filling firstname lastname and phone, then everything going well except one thing that in my MYSQL database data is save as firstname: NULL lastname:NULL And phone:NULL instead of saving the data which i had enter.
I have a angularjs form in which is there fields like firstname lastname and phone.on submit it goes to submitContact() in controller:
submit.js:
var addnew = angular.module('addnew',[]);
// create angular controller
addnew.controller('addContactController',
function($scope,$location,$window,$http) {
// function to submit the form after all validation has occurred
$scope.submitContact = function() {
$scope.addnew = {firstname:'', lastname:'',phone:''};
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
$http.get("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
};
});
http://localhost:8000/index.php/user/addnew this links to my laravel through routes.
my route.php:
Route::get('/user/addnew', 'usercontroller#store');
my usercontroller.php
public function store(Request $request)
{
//contacts::create(Request::all());
$user = new contacts;// contacts is my table name and my database is defined in .env file
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->phone = Input::get('phone');
$user->save();
//I Used print_r to see that weather my submitted data is coming in $user or not:
print_r($user);
echo "saved";
}
my contact.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class contacts extends Model
{
protected $fillable =['firstname','lastname','phone'];
}
?>
Now, My problem
when i print_r $user then i got the error as my array is NOT catching my submitted data
print_r ($user) output in console window:
[fillable:protected] => Array
(
[0] => firstname
[1] => lastname
[2] => phone
)
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
[original:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
I want to know where I m making mistake and how can I correct that mistake.
Thanking you in anticipation.
Try this:
$user = new Contact();
Instead of this:
$user = new contacts;
Also, change class name to class Contact extends Model and a filename to a Contact.php.
Alternatively, since you're using $fillable you can create new row:
Contact::create($request->all());
https://laravel.com/docs/5.3/eloquent#mass-assignment
I think you should use POST instead of GET.
$http.post("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
And
Route::post('/user/addnew', 'usercontroller#store');
And I noticed that you are posting to /index.php/user/addnew
And your route is '/user/addnew'
'/index.php/user/addnew' and '/user/addnew' are different.
try posting to localhost:8000/user/addnew instead
To explain:
/user/addnew always refer to host:port/user/addnew
While user/addnew will just concatenate it to your current url
for example if you're currently at: localhost:8000/users/1
Clicking a link to user/addnew will bring you to localhost:8000/users/1/user/addnew while a link to /user/addnew will bring you to localhost:8000/user/addnew
EDIT:
Is this redundant?
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
What you were sending is this:
{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname}
I think you can send this instead:
$scope.addnew
and again, you should use POST, not GET.
did you already update your http request to post? did you update the url?
Actually, I achived this by using $request->input('firstname'); $request->input('firstname'); $request->input('firstname');, since, it was JSON thats why. Else, If I had been using Laravel blade file then I could have done it by above solutions.
Related
I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.
I'm having an issue rendering a Twig view and a JSON response, I need to call the twig view and pass it a new Json response with a variable as parameter. The output error is the following "Notice: Object of class Symfony\Component\HttpFoundation\Response could not be converted to int
"
Here is the code
$resultado = array('mes1_local' => $mes1_local, 'mes2_local' => $mes2_local, 'mes3_local' => $mes3_local, 'mes1_online' => $mes1_online, 'mes2_online' => $mes2_online, 'mes3_online' => $mes3_online, 'contador_pedido_local' => $contador_pedido_local, 'contador_pedido_online' => $contador_pedido_online, 'contador_total' => $contador_total, 'contador_usuarios' => $contador_usuarios);
return new JsonResponse($resultado, $this->render('others/adminlte.html.twig'));
Like #goto's answer, but it won't works, cause you need to use renderView instead of render:
return new JsonResponse([
'things' => $thingsArray,
'anotherVariable' => $simpleVariable,
'html' => $this->renderView('others/adminlte.html.twig', []/* template parameters goes here */),
]);
The Json Response signature is
__construct(mixed $data = null, int $status = 200, array $headers = array(), bool $json = false)
You are trying to give the twig to the status parameter.
You can avoid this silly error by using a good IDE
To give additional data to your response you could structure your array data returned
return new JsonResponse([
'someData' => $resultado,
'html' => $this->render('others/adminlte.html.twig')
);
i'm creating an application in symfony 2.8 (with php5.4) and in my form (that i'm building) i want to display a list of a projects through an API in json format.
Now i'm stuck, and i don't know how to do this.
I know the database of the API there is a table "projects" and i want target the column 'name' to display names of projects
here's my code:
/**
* #Route("/form")
*/
public function formAction(Request $request)
{
$url = 'https://website.com/projects.json';
$get_json = file_get_contents($url);
$json = json_decode($get_json);
$form = $this->createFormBuilder()
->add('Project', 'choice') // <-- ???
->add('send', 'submit' ,array('label' => 'Envoyer'))
->getForm();
$form->handleRequest($request);
return $this->render('StatBundle:Default:form.html.twig', array('form' => $form->createView(), 'project' => $json));
}
You can pass the choice as second argument as array as example:
$jsonAsArray = json_decode($get_json, true); // with true return an array
$builder->add('Project', 'choice', array(
'choices' => $jsonAsArray,
// *this line is important, depends of the data*
'choices_as_values' => false,
));
More info in the doc here.
Hope this help
I have integrated braintree method in yii2 rest api Using this reference.. I want to update the customer but I am getting following error:
Missing argument 2 for Braintree\Customer::update()
Below is my code :
$braintree = Yii::$app->braintree;
$response = $braintree->call('Customer', 'update','15552090',[
'firstName' => 'test-1545',
'lastName' => 'asdf',
'company' => 'New Company',
'email' => 'new.email#example.com',
'phone' => 'new phone',
'fax' => 'new fax',
'website' => 'http://new.example.com'
]);
print_r($response); die;
I am stack here how to pass the arguments?
It's a problem of this particular extension. See this issue on Github.
Issue OP recommends this fix:
public function call($command, $method, $values, $values2 = null)
{
$class = strtr("{class}_{command}", [
'{class}' => $this->_prefix,
'{command}' => $command,
));
if ($values2) {
return call_user_func(array($class, $method), $values, $values2);
else {
return call_user_func(array($class, $method), $values);
}
}
while extension author recommends this:
if (is_array($values)) {
call_user_func_array(...);
} else {
call_user_func(...);
}
Either way you need to override this component with your own and apply a patch.
Note that the amount of code in application is small (64 lines in one file) so you can create your own wrapper or find better one because this issue is still not fixed.
And maybe is better to directly use braintree_php methods which will be more clear than magical call.
Update: To override component, create own class extending from bryglen's, place it for example in common/components folder in case of using advanced app.
namespace common\components;
class Braintree extends \bryglen\braintree\Braintree
{
public function call($command, $method, $values)
{
// Override logic here
}
}
Then replace extension class name with your custom one in config:
'components' => [
'braintree' => [
'class' => 'common\components\Braintree',
'environment' => 'sandbox',
'merchantId' => 'your_merchant_id',
'publicKey' => 'your_public_key',
'privateKey' => 'your_private_key',
],
],
I have tried everything I know to do but I cannot seem to get this to work...
My goal is to show tickets submitted in the past two weeks. I have already done all the logic on the back side of my MVC project but I cannot seem to display it properly. I just get a blank line graph with the legend to the right. I have provided my Razor code and the JSON return data. Please help. Thanks.
#(Html.Kendo().Chart<NewTicketsTwoWeekGraph>()
.Name("TwoWeekTickets")
.DataSource(dataSource => dataSource
.Read(read => read.Action("NewTicketsData_Read", "Home"))
)
.Series(series =>
{
series.Line(d => d.TicketCount).Name("Ticket Count");
})
.CategoryAxis(axis => axis
.Categories(t => t.TicketDate).Date().BaseUnit(ChartAxisBaseUnit.Days)
.Labels(labels => labels.Rotation(-90))
.Crosshair(c => c.Visible(true))
)
.ValueAxis(axis => axis.Numeric()
.Labels(labels => labels.Format("{0:N0}"))
.MajorUnit(10)
)
)
JSON Return:
{"Data":[{"TicketCount":1,"TicketDate":"\/Date(1426651200000)\/","TicketDateString":"2015-03-18"},
{"TicketCount":2,"TicketDate":"\/Date(1426564800000)\/","TicketDateString":"2015-03-17"}],"Total":2,"AggregateResults":null,"Errors":null}
The problem was with the JSON data being sent back. It doesnt like be wrapped in the "Data" array.
So I changed up my ActionResult to fix this...
public ActionResult _NewTicketCtOverTwoWeeks_Read([DataSourceRequest]DataSourceRequest request, string username)
{
using (var ctx = new GuardianContext())
{
var startDate = DateTime.Now.AddDays(-14);
var graphData = from ticket in ctx.TICKETS
where ticket.CREATED > startDate
group ticket by DbFunctions.TruncateTime(ticket.CREATED)
into a
orderby a.Key
select new TicketCount() { TicketCt = a.Count(), TicketDate = (DateTime)a.Key, TicketDateString = a.Key.ToString().Substring(0, 10) };
return Json(graphData.ToList());
}
}
So now my JSON request returns the following...
[{"TicketCt":2,"TicketDate":"\/Date(1426564800000)\/","TicketDateString":"2015-03-17"},{"TicketCt":11,"TicketDate":"\/Date(1426651200000)\/","TicketDateString":"2015-03-18"},{"TicketCt":20,"TicketDate":"\/Date(1426737600000)\/","TicketDateString":"2015-03-19"}]