laravel 8 add row and write userid automatically? - database

I followed this quida, and everything works, but I need that the userid field is automatically written with the id of the logged in user, how can I do it? how can i add this to this code?
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ProductStock;
class ProductAddMoreController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function addMore()
{
return view("addMore");
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function addMorePost(Request $request)
{
$request->validate([
'addmore.*.name' => 'required',
'addmore.*.qty' => 'required',
'addmore.*.price' => 'required',
]);
foreach ($request->addmore as $key => $value) {
ProductStock::create($value);
}
return back()->with('success', 'Record Created Successfully.');
}
}
view:
<!DOCTYPE html>
<html>
<head>
<title>Add/remove multiple input fields dynamically with Jquery Laravel 5.8</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2 align="center">Add/remove multiple input fields dynamically with Jquery Laravel 5.8</h2>
<form action="{{ route('addmorePost') }}" method="POST">
#csrf
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if (Session::has('success'))
<div class="alert alert-success text-center">
×
<p>{{ Session::get('success') }}</p>
</div>
#endif
<table class="table table-bordered" id="dynamicTable">
<tr>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr>
<td><input type="text" name="addmore[0][name]" placeholder="Enter your Name" class="form-control" /></td>
<td><input type="text" name="addmore[0][qty]" placeholder="Enter your Qty" class="form-control" /></td>
<td><input type="text" name="addmore[0][price]" placeholder="Enter your Price" class="form-control" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<button type="submit" class="btn btn-success">Save</button>
</form>
</div>
<script type="text/javascript">
var i = 0;
$("#add").click(function(){
++i;
$("#dynamicTable").append('<tr><td><input type="text" name="addmore['+i+'][name]" placeholder="Enter your Name" class="form-control" /></td><td><input type="text" name="addmore['+i+'][qty]" placeholder="Enter your Qty" class="form-control" /></td><td><input type="text" name="addmore['+i+'][price]" placeholder="Enter your Price" class="form-control" /></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
});
$(document).on('click', '.remove-tr', function(){
$(this).parents('tr').remove();
});
</script>
</body>
</html>
Does anyone know how to help me insert userid in the database automatically, I don't need to see it in the table but I need it to be registered in the database with these associated fields

Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. Userid can be obtained like this Auth::user()->id
Use this identifier in your code ProductAddMoreController for ProductStock model.

There is more than one way to do this, you might do it using Model observers or you can do it by adding user_id value manually to create method.
First you need to have the user_id column in your products_stocks DB table, you can add it to your up() method in your migration using something like:
public function up()
{
Schema::table('products_stocks', function (Blueprint $table) {
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade')->onUpdate('cascade');
});
}
then in your controller add the user_id to create() method:
// ...
foreach ($request->addmore as $key => $value) {
ProductStock::create(array_merge($value, ['user_id' => auth()->user()->id]));
}
// ...

Related

Getting the id of the form from table as reference to the next form in Laravel

I am very new to Laravel. I am currently doing a Laravel project where a person can submit a proposal. The Laravel version I'm using is Laravel Framework 8. I divided the proposal form into 7 pages. I also have 7 tables in the database. So the data of each page will be saved into each of the tables. 1 page = 1 table. This means I also have 7 models. In conclusion, I have 7 views, 7 controllers, 7 models, and 7 tables (if this is not a good practice please tell me)
Here is an example of my code
Route
web.php
Route::get('/form/details', [App\Http\Controllers\Lect\Form\Step1Controller::class, 'createStepOne'])->name('form.create.step.one');
Route::post('/form/details', [App\Http\Controllers\Lect\Form\Step1Controller::class, 'postCreateStepOne'])->name('form.create.step.one.post');
Route::get('/form/learning-outcomes', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'createStepTwo'])->name('form.create.step.two');
Route::post('/form/learning-outcomes', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'postCreateStepTwo'])->name('form.create.step.two.post');
...
Model
Step1.php
class Step1 extends Model {
use HasFactory;
public $table = 'forms';
protected $fillable = [
'title',
'code',
'creditvalue',
'mqflevel',
'affectedbatch',
'kulliyyah',
'department',
'synopsis',
'classification',
'prerequisite',
];
}
Step2.php
class Step2 extends Model {
use HasFactory;
public $table = 'proposal_learning_outcome';
public $timestamps = false;
protected $fillable = [
'proposal_id',
'lo_id',
'outcomes',
'bloom_c',
'bloom_a',
'bloom_p',
'ki',
'po',
];
}
Controller
Step1Controller.php
class Step1Controller extends Controller {
public function createStepOne(Request $request) {
return view('form.step1');
}
public function postCreateStepOne(Request $request) {
$validatedData = $request->validate([
'title' => 'required',
'code' => 'required|unique:forms',
'creditvalue' => 'required|numeric',
'mqflevel' => 'required|numeric',
'affectedbatch' => 'required',
'kulliyyah' => 'required',
'department' => 'required',
'synopsis' => 'required',
'classification' => 'required',
'prerequisite' => 'required',
]);
$step1 = new Step1;
$step1->title=$request->input('title');
$step1->code=$request->input('code');
$step1->creditvalue=$request->input('creditvalue');
$step1->mqflevel=$request->input('mqflevel');
$step1->affectedbatch=$request->input('affectedbatch');
$step1->kulliyyah=$request->input('kulliyyah');
$step1->department=$request->input('department');
$step1->synopsis=$request->input('synopsis');
$step1->classification=$request->input('classification');
$step1->prerequisite=$request->input('prerequisite');
$step1->created_by=Auth::user()->username;
$result = $step1->save();
return redirect()->route('form.create.step.two');
}
}
Step2Controller.php
class Step2Controller extends Controller {
public function createStepTwo(Request $request) {
return view('form.step2');
}
public function postCreateStepTwo(Request $request) {
$validatedData = $request->validate([
'proposal_id' => 'required',
'lo_id' => 'required',
'outcomes' => 'required',
'bloom_c' => 'required',
'bloom_a' => 'required',
'bloom_p' => 'required',
'ki' => 'required',
'po' => 'required',
]);
foreach($request->lo_id as $key=>$lo_id) {
$data = new Step2();
$data->proposal_id=$request->input('proposal_id');
$data->lo_id=$lo_id;
$data->outcomes=$request->outcomes[$key];
$data->bloom_c=$request->bloom_c[$key];
$data->bloom_a=$request->bloom_a[$key];
$data->bloom_p=$request->bloom_p[$key];
$data->ki=$request->ki[$key];
$data->po=$request->po[$key];
$data->save();
}
return redirect()->route('form.create.step.three');
}
}
View
step1.blade.php
<form action="{{ route('form.create.step.one.post') }}" method="POST">
#csrf
<div class="card">
Step 1: Basic Info
</div>
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label for="title">Course Title</label>
<input type="text" name="title" class="form-control text-lg" id="title" placeholder="">
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="code">Course Code</label>
<input type="text" name="code" class="form-control text-lg" id="code" placeholder="">
</div>
<div class="form-group">
<label for="creditvalue">Credit Value</label>
<input type="number" name="creditvalue" class="form-control text-lg" id="creditvalue" placeholder="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="mqflevel">MQF Level</label>
<input type="number" name="mqflevel" class="form-control text-lg" id="mqflevel" placeholder="">
</div>
<div class="form-group">
<label for="affectedbatch">Affected Batch</label>
<input type="text" name="affectedbatch" class="form-control text-lg" id="affectedbatch" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<label for="kulliyyah">Centre of Studies</label>
<select type="text" class="form-control text-lg" name="kulliyyah" id="kulliyyah">
<option value="Kulliyyah of Information and Communication Technology">Kulliyyah of Information and Communication Technology</option>
<option value="Kulliyyah of Education">Kulliyyah of Education</option>
<option value="Kulliyyah of Engineering">Kulliyyah of Engineering</option>
<option value="Kulliyyah of Architecture and Environmental Design">Kulliyyah of Architecture and Environmental Design</option>
</select>
</div>
<div class="form-group">
<label for="department">Department/Unit</label>
<select type="text" class="form-control text-lg" name="department" id="department">
<option value="Department of Computer Science">Department of Computer Science</option>
<option value="Department of Information System">Department of Information System</option>
</select>
</div>
<div class="form-group">
<label for="synopsis">Course Synopsis</label>
<textarea type="text" class="form-control text-lg" name="synopsis" rows="5" id="synopsis" placeholder=""></textarea>
</div>
<div class="form-group">
<label for="classification">Course Classification within the Curriculum</label>
<input type="text" class="form-control text-lg" name="classification" id="classification" placeholder="eg: CSC 1305">
</div>
<div class="form-group">
<label for="prerequisite">Prerequisite(s) (if any)</label>
<input type="text" class="form-control text-lg" name="prerequisite" id="prerequisite" placeholder="">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</div>
</form>
step2.blade.php
<form action="{{ route('form.create.step.two.post') }}" method="POST">
#csrf
<div class="card">
Step 2: Course Learning Outcomes</div>
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label for="proposal_id">Proposal ID</label>
<input type="text" class="form-control text-lg" name="proposal_id" id="proposal_id" placeholder="">
</div>
<div class="table-responsive">
<form method="post" id="dynamic_form">
<span id="result"></span>
<table class="table table-bordered" id="user_table">
<thead>
<tr class="table-active">
<th rowspan="2">No.</th>
<th rowspan="2" class="w-50">Outcomes</th>
<th colspan="3" class="w-25">Bloom's Taxonomy</th>
<th rowspan="2">Soft skills (KI)</th>
<th rowspan="2">Programme Outcomes (PO)</th>
<th rowspan="2">Add</th>
</tr>
<tr class="table-active">
<th>C</th>
<th>A</th>
<th>P</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control text-lg" name="lo_id[]"/></td>
<td><textarea class="form-control text-lg" name="outcomes[]"></textarea></td>
<td><input class="form-control text-lg" name="bloom_c[]"/></td>
<td><input class="form-control text-lg" name="bloom_a[]"/></td>
<td><input class="form-control text-lg" name="bloom_p[]"/></td>
<td><input class="form-control text-lg" name="ki[]"/></td>
<td><input class="form-control text-lg" name="po[]"/></td>
<td>Remove</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-6 text-left">
Previous
</div>
<div class="col-md-6 text-right">
<button type="submit" class="btn btn-primary ">Next</button>
</div>
</div>
</div>
</div>
</form>
and the other 5 steps are basically like that.
My current problem is how can I get the proposal_id of the first form (step1) as a reference to the next 6 forms. The proposal_id is used as a foreign key for other tables. The proposal_id is auto-incremented in the table.
The reason I divided them into many tables is that some parts of the form are in table format as shown in step2.blade.php. The image below a reference.
Form example
For now, as you can see in the code, my current solution is to manually input the proposal_id in each form (which is not practical because they would not know the proposal_id in the first place). My current code has no issue. It can be saved into the database as normal.
How can I solve this issue? Or is there another way to fill up this form? Thank you in advance.
You have two solution, the first I see is to pass the proposal_id as a parameter of your route (see below).
Route::get('/form/learning-outcomes{proposal_id}', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'createStepTwo'])->name('form.create.step.two');
The second is to save it in your session variable and you can acess it throught your form
session()->put('proposal_id', $proposal_id)
To get it in your second form use :
session()->get('proposal_id')
Update
Make sure to add this line in your migration file:
$table->id('proposal_id')
where the proposal_id is your primary key autoincrement. By default if you don't put anything as id parameter, it will be id in your column table.
$table->id()//COLUMN TABLE WILL CONTAINT id as name
$table->id('proposal_id')//COLMUN TABLE WILL CONTAINT proposal_id as name
The answer was helpful but not actually what I asked (sorry if my question was not clear). I found the answer to my question.
I wanted to get the proposal_id from the first form. I called the lastest added row in the table like this:
$proposal_id = DB::table('forms')
->select('proposal_id')
->orderBy('proposal_id', 'desc')
->limit(1)
->value('proposal_id');
I added this code in the Step1Controller after
$result = $step1->save();
And then I save it into session like crazy4dev suggested:
$request->session()->put('proposal_id', $proposal_id);
return redirect()->route('form.create.step.two', compact('proposal_id'));
I can access the proposal_id in the Step2Controller with:
$proposal_id = $request->session()->get('proposal_id');

AngularJs Form Model Not Submitting via Ajax

I can't get the values of the form passed via ajax. I used angularJs model. Please help. My codes below.
for hmtl:
<form role="form" ng-submit="submit_new_rpo(new_rpo)">
<div class="box-body">
<table class="table table-striped">
<tbody>
<tr>
<td>RPO# :
<input type="text"
class="form-control" ng-model="new_rpo.po_number" required="required">
</td>
</tr>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Ajax:
$scope.submit_new_rpo=function(rpo)
{
$http({
method : "POST",
url : burl + "po/insert_po_manual"
,data:{"rpo":rpo}
}).then(function(response){
alert(response.data);
}, function myError(response) {
$scope.err_content=response.data;
});
}
php
public function insert_po_manual()
{
$params = json_decode(file_get_contents('php://input'),true);
if(!isset($params))
{
show_404();
}
echo $params['rpo']['po_number'];
}
I am getting empty array in my server. I used the code in other modules and its working.But this time I don't know why Im getting empty values.

How To Solve This Update Error In Laravel

I'm creating a web site. And I have created a registration page. I want to update my details.
But, It gives me this error and I have also uploaded a picture of errors below. -
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
** Error Picture
How can I Fix this ??
Here is my AdminPanel.blade.php
<table class="table table-bordered">
<tr>
<td> Name </td>
<td> Email </td>
<td> Images </td>
</tr>
#foreach($data as $value )
<tr>
<td> {{ $value->username }} </td>
<td> {{ $value->email }} </td>
<td> <img src='{{ $value->filemove }}' style='width:100px;height:100px;'> </td>
<td> <input type="submit" name="update" value="Update" class="btn-primary"> </td>
<td> <input type="submit" name="delete" value="Delete" class="btn-danger"> </td>
</tr>
#endforeach
</table>
Here is my AdminUpdate.blade.php
<form action="edit{{ $users[0]->id }}" method="post" enctype="multipart/form-data">
{{ method_field('PUT') }}
{{ csrf_field() }}
<div class="form-group">
<label>Username : *</label>
<input type="text" class="form-control" name="username" value="{{$users[0]->username}}" placeholder="Enter Your Username" required>
</div>
<div class="form-group">
<label>Email : *</label>
<input type="email" class="form-control" name="email" value="{{$users[0]->email}}" placeholder="Enter Your Username" required>
</div>
<div class="form-group">
<label>Password : *</label>
<input type="password" class="form-control" name="password" value="{{$users[0]->password}}" placeholder="Enter Your Password" required>
</div>
<div class="form-group">
<label>Upload Profile Picture :</label>
<input type="file" class="form-control-file" name="file_img" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">If U Want , U Can Skip Upload A Profile Picture</small>
</div>
#section('btnName',"Update")
<input type="submit" class="btn btn-primary" onclick="myFunction()" name="submit" value="#yield('btnName')">
</form>
Here is my AdminPanelController.php
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\User;
use Validator;
use Illuminate\Support\Facades\Input;
class AdminPanelController extends Controller
{
public function index()
{
$data = User::all();
//$data = login::orderBy('created_at', 'desc')->get();
return view('AdminPanel', ['data' => $data]);
}
public function adminedit(Request $request, $id)
{
$this->validate($request, [
'email' => 'required'
]);
$users = User::find($request['id']);
$users->username = $request['username'];
$users->email = $request['email'];
$users->update();
return redirect('AdminPanel');
}
}
Here is my Route
Route::put('edit/{id}','AdminPanelController#adminedit');
you should replace your action url
//make sure you have $users[0]->id data here
<form action="{{ action('AdminPanelController#adminedit',['id'=> $users[0]->id]) }}" ....>

Passing results from Laravel 5.2 to view using AngularJS does not work correctly

I am learning how to intergrate Angular in my Laravel app. But when I select values from a database table its displayed in the browser in Json format like shown:
[{"id":1,"product_name":"smart phone"},
[{"id":2,"product_name":"laptop"},
[{"id":3,"product_name":"desktop"},
[{"id":4,"product_name":"tablet"}]
I want my result in the view to look as so:
id product Name
1 Smart Phone
2 Laptop
3 Desktop
4 tablet
My productsController.php listProducts()
//List all products
public function listProducts($id = null) {
if ($id == null) {
return Product::orderBy('id', 'asc')->get();
} else {
return $this->show($id);
}
}
My show products method:
public function show($id)
{
return Product::find($id);
}
my routes.php
Route::group(array('prefix' => 'api'), function() {
Route::get('/v1/products/{id?}' ,['as'=>'productindex','uses'=>'ProductsController#listProducts']);
Route::post('/v1/products', 'ProductsController#store');
Route::post('/v1/products/{id}', 'ProductsController#update');
Route::post('/v1/products/update/{id}',['as'=>'update','uses'=> 'ProductsController#update']);
Route::delete('/v1/products/{id}', 'ProductsController#destroy');
});
My productsController.js
//public/app/controllers/productsController.js
app.controller('productsController', function($scope, $http, API_URL) {
//retrieve products listing from API
$http.get(API_URL + "products")
.success(function(response) {
$scope.products = response;
});
//show modal form
$scope.toggle = function(modalstate, id) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Add New Product";
break;
case 'edit':
$scope.form_title = "Product Detail";
$scope.id = id;
$http.get(API_URL + 'products/' + id)
.success(function(response) {
console.log(response);
$scope.product = response;
});
break;
default:
break;
}
console.log(id);
$('#myModal').modal('show');
}
//save new record / update existing record
$scope.save = function(modalstate, id) {
var url = API_URL + "products";
//append employee id to the URL if the form is in edit mode
if (modalstate === 'edit'){
url += "/" + id;
}
$http({
method: 'POST',
url: url,
data: $.param($scope.Product),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
//delete record
$scope.confirmDelete = function(id) {
var isConfirmDelete = confirm('Are you sure you want this record?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'products/' + id
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Unable to delete');
});
} else {
return false;
}
}
});
My app.js
//public/app/app.js
var app = angular.module('products', [])
.constant('API_URL', 'http://localhost/myapp/public/api/v1/');
my view
// resources/views/products/listproducts.php
<!DOCTYPE html>
<html lang="en-US" ng-app="products">
<head>
<title>Laravel 5 AngularJS CRUD Example</title>
<!-- Load Bootstrap CSS -->
<link href="<?= asset('css/bootstrap.min.css') ?>" rel="stylesheet">
</head>
<body>
<h2>Employees Database</h2>
<div ng-controller="productsController">
<!-- Table-to-load-the-data Part -->
<table class="table">
<thead>
<tr>
<th>Product Id</th>
<th>Product Name</th>
<th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Product</button></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products">
<td>{{ product.proudct_id }}</td>
<td>{{ product.product_name }}</td>
<td>
<button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', product.id)">Edit</button>
<button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(product.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<!-- End of Table-to-load-the-data Part -->
<!-- Modal (Pop up when detail button clicked) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">{{form_title}}</h4>
</div>
<div class="modal-body">
<form name="frmEmployees" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputEmail3" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
ng-model="employee.name" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.name.$invalid && frmEmployees.name.$touched">Name field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
ng-model="employee.email" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.email.$invalid && frmEmployees.email.$touched">Valid Email field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Contact Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
ng-model="employee.contact_number" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.contact_number.$invalid && frmEmployees.contact_number.$touched">Contact number field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Position</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
ng-model="employee.position" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.position.$invalid && frmEmployees.position.$touched">Position field is required</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<!-- Load Javascript Libraries (AngularJS, JQuery, Bootstrap) -->
<script src="<?= asset('app/lib/angular/angular.min.js') ?>"></script>
<script src="<?= asset('js/jquery.min.js') ?>"></script>
<script src="<?= asset('js/bootstrap.min.js') ?>"></script>
<!-- AngularJS Application Scripts -->
<script src="<?= asset('app/app.js') ?>"></script>
<script src="<?= asset('app/controllers/productsController.js') ?>"></script>
</body>
</html>
My question is what May I doing wrong. Its like the listProducts method in productsController.php is not passing results to listproducts.php. What should I do? Kindly assist.
Laravel and angular notations overlap (both blade and angular use '{{' to output variables). I had to change angular behaviour using:
app.config(['$interpolateProvider',
function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}])
I guess you can do something similar on Laravel, but I don't know how.
that problem solved, you could try and output the content of '$scope.products' in the html page, to see if it is what you expect. The response to the api call seems ok, so the problem likely lies in the angular side.

AngularJS Form submit

Working on my first small AngularJS App I'm facing problems with a form submit. I worked trough the CodeSchool course and figured the most out by myself, but this form submit thingy... well I just don't get where I'm wrong so that's why it would be nice if you could show me the right solution, so I can go on.
Project: A simple Workout List where you can list all the training sessions you had. This is my HTML, Element 3 is the problem:
<header class="wob-masthead container-fluid">
<div class="row">
<div class="col-md-6" ng-init="tab = 1">
<ul class="nav nav-pills">
<li ng-class="{ active:tab === 1 }"><a href ng-click="tab = 1">Overview</a></li>
<li ng-class="{ active:tab === 2}"><a href ng-click="tab = 2">Stats</a></li>
<li ng-class="{ active:tab === 3 }"><a href ng-click="tab = 3">New</a></li>
</ul>
</div>
<div class="col-md-6">
<form class="navbar-form pull-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
</div>
</div>
</header>
<section class="wob-main mainlist container" id="headjump">
<!--- ==========================================
Element 1: Overview
============================================= -->
<div class="subsite" ng-show="tab === 1">
<div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
<h1>WorkoutBuddy</h1>
<div class="table-responsive" ng-controller="ListController as listing">
<table class="table table-hover">
<thead>
<tr>
<th class="col-md-2">Date</th>
<th class="col-md-8">Type</th>
<th class="col-md-1">Repeat</th>
<th class="col-md-1">Time</th>
</tr>
</thead>
<tbody ng-controller="ListController as listing">
<tr ng-repeat="wo in listing.sessions">
<td>{{wo.date | date:'dd/MM/yyyy'}} </td>
<td>{{wo.name}}</td>
<td>{{wo.repeat}}</td>
<td>{{wo.time}} Minutes</td>
</tr>
</tbody>
</table>
</div>
</div>
<!--- ==========================================
Element 2: Stats
============================================= -->
<div class="subsite" ng-show="tab === 2">
<div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
<h1>Stats</h1>
<!-- Ende Subsite -->
</div>
<!--- ==========================================
Element 3: New
============================================= -->
<div class="subsite" ng-show="tab === 3">
<div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
<h1>New</h1>
<div class="table-responsive" ng-controller="ListController as listing">
<table class="table table-hover">
<thead>
<tr>
<th class="col-md-2">Date</th>
<th class="col-md-8">Type</th>
<th class="col-md-1">Repeat</th>
<th class="col-md-1">Time</th>
</tr>
</thead>
<tbody ng-controller="ListController as listing">
<tr ng-repeat="wo in listing.sessions | limitTo:2">
<td>{{wo.date | date:'dd/MM/yyyy'}} </td>
<td>{{wo.name}}</td>
<td>{{wo.repeat}}</td>
<td>{{wo.time}} minutes</td>
</tr>
</tbody>
</table>
</div>
<form name="WorkoutForm" ng-controller="EntryController as entryCtrl">
<blockquote>
<h3>Last Workout:</h3>
<strong>{{entryCtrl.wo.name}}</strong><br>
<small>am: {{entryCtrl.wo.date}}</small><br>
{{entryCtrl.wo.repeat}} repeats in {{wo.time}} minutes.
</blockquote>
<input ng-model="entryCtrl.wo.date" type="date" placeholder="date" />
<input ng-model="entryCtrl.wo.name" type="name" placeholder="name" />
<input ng-model="entryCtrl.wo.repeat" type="repeat" placeholder="repeat" />
<input ng-model="entryCtrl.wo.time" type="time" placeholder="time" />
<input type="submit" value="Add" />
</form>
<!-- Ende Subsite -->
</div>
</section>
I styled it with Bootstrap and this is my app.js:
(function(){
var app = angular.module('wobuddy', [ ]);
app.controller('ListController', function(){
this.sessions = wos;
});
var wos = [
{
name: 'Squat',
date: '01.01.2015',
repeat: 50,
time: 10
},
{
name: 'Push Ups',
date: '01.01.2015',
repeat: 50,
time: 10
}
];
})();
Switching between the sections using the nav works pretty fine and also printing out the data-elements in the table, but when I push submit nothing happens - really hope you can help me to learn :-)
You need to make an EntryController that will add a new object to the end of the wos collection. Something like this:
app.controller('EntryController', function($scope) {
$scope.wo = {};
$scope.submit = function() {
wos.push($scope.wo);
$scope.wo = {}; // Clear the form fields
};
});
Then your HTML for that section could look something like this:
<form name="WorkoutForm" ng-controller="EntryController">
<blockquote>
<h3>Last Workout:</h3>
<strong>{{wo.name}}</strong><br>
<small>am: {{wo.date}}</small><br>
{{wo.repeat}} repeats in {{wo.time}} minutes.
</blockquote>
<input ng-model="wo.date" type="date" placeholder="date" />
<input ng-model="wo.name" type="name" placeholder="name" />
<input ng-model="wo.repeat" type="repeat" placeholder="repeat" />
<input ng-model="wo.time" type="time" placeholder="time" />
<button ng-click="submit()">Add</button>
</form>
Notice that it's more usual for a controller to communicate data to the template via the $scope object rather than via the controller object itself.
By looking at you form HTML, I think you missed the name attribute inside your form and also ng-submit directive is missing which will gets called after a submit form. Do check form validation inside controller using $valid() method and perform post else give alert to user.
HTML
<form name="workoutForm" ng-controller="ReviewController as reviewCtrl" ng-submit="submit(workoutForm, entryCtrl.wo)">
<blockquote>
<h3>Last Workout:</h3>
<strong>{{entryCtrl.wo.name}}</strong>
<br>
<small>am: {{entryCtrl.wo.date}}</small>
<br> {{entryCtrl.wo.repeat}} repeats in {{wo.time}} minutes.
</blockquote>
<input name="date" ng-model="entryCtrl.wo.date" type="date" placeholder="date" />
<input name="name" ng-model="entryCtrl.wo.name" type="name" placeholder="name" />
<input name="repeat" ng-model="entryCtrl.wo.repeat" type="repeat" placeholder="repeat" />
<input name="time" ng-model="entryCtrl.wo.time" type="time" placeholder="time" />
<input type="submit" value="Add" />
</form>
Controller
$scope.submit = function(workoutForm, item){
if(workoutForm.$valid)
//then make $http.post by sending item values
else
//show error
};
UPDATE
<html ng-app='demoApp'>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<form ng-controller="validationCtrl">
<input type="text" placeholder="Name...." ng-model="user.name"/>
<input type="text" placeholder="Password...." ng-model="user.pass"/>
<input type="text" placeholder="Mobile...." ng-model="user.mo"/>
<input type="submit" ng-click="alldata(user)"/>
</form>
<script>
//This is controller
var app = angular.module('demoApp', []);
app.controller('validationCtrl', function($scope) {
$scope.alldata=function(user)
{
alert(JSON.stringify(user));
}
});
</script>
</body>
</html>
You can also use this method, and
Your form shoud be like
<form method="post" name="sentMessage" id="my_contact" novalidate="novalidate">
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Name</label>
<input class="form-control" id="name" type="text" name="name" placeholder="Name" required="required" data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Email Address</label>
<input class="form-control" id="email" type="email" name="email" placeholder="Email Address" required="required" data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Phone Number</label>
<input class="form-control" id="phone" type="tel" name="phone" placeholder="Phone Number" required="required" data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Message</label>
<textarea class="form-control" id="message" rows="5" name="Message" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
Send
</div>
</form
import jquery as below
npm install jquery using CLI
import * as $ from 'jquery';
send_query() function will be
send_query() {
var data = $("#my_contact").serializeArray();
var indxarr = {};
$.each(data,function(i,v){
indxarr[v['name']] = v['value'];
});
data = JSON.parse(JSON.stringify(indxarr))
//POST YOUR DATA
this.httpClient.post('http://localhost/rajat/ajax/contact_query_submit/', data,httpOptions)
.subscribe(data => {
console.log(data);
});
}
Your backend code will be
public function contact_query_submit(){
if ($this->input->post()) {
$postdata = file_get_contents("php://input");
$_POST = json_decode($postdata,TRUE);
$addArr = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'message' => $this->input->post('message'),
'created' => time()
);
if($this->main_model->create('rjt_contact', $addArr)){
$arr[] = array('type' => 'success', 'msg' => '<p>Your query has been received. <br>We will get back to you soon.</p>');
echo json_encode($arr);
}else{
$arr[] = array('type' => 'warning', 'msg' => '<p>'.$this->db->last_query().'</p>');
echo json_encode($arr);
}
}else{
$arr[] = array('type' => 'warning', 'msg' => '<p>No data post yet</p>');
echo json_encode($arr);
}
}

Resources