DB Transaction in Laravel lexical variable error - database

I'm currently using DB-Transaction and it throws Lexical variable error
attached here is my code:
DB::transaction(function ($request) use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}

It is working now after I remove the $request parameter in function
DB::transaction(function () use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}

Related

How to pass array inside an api in Laravel?

When I pass array() through query it got false but when I pass without array then it show success. How can I pass array according to my code?
public function add_employee_post(Request $request){
try{
$http = new \GuzzleHttp\Client();
$employee_no = $request->employee_no;
$name = $request->name;
$nid = $request->nid;
$dob = $request->dob;
$covid_status = $request->covid_status;
$vaccine_certificate = $request->vaccine_certificate;
$official_email = $request->official_email;
$optional_email = array();
if($request->optional_email[0] != null){
foreach (json_decode($request->optional_email[0]) as $key => $email) {
array_push($optional_email, $email->value);
}
}
$official_phone = $request->official_phone;
$optional_phone = array();
if($request->optional_phone[0] != null){
foreach (json_decode($request->optional_phone[0]) as $key => $phone) {
array_push($optional_phone, $phone->value);
}
}
$designation = $request->designation;
$employee_type = $request->employee_type;
$role = $request->role;
$department = $request->department;
$team = $request->team;
$grade = $request->grade;
$level = $request->level;
$avatar = $request->avatar;
$present_address = $request->present_address;
$permanent_address = $request->permanent_address;
$employee_status = $request->employee_status;
$employee_invitation_status = $request->employee_invitation_status;
$response = $http->post('http://localhost:8000/api/v1/employees/create',[
// 'headers' => [
// 'Authorization' => 'Bearer'.session()->get('token.access_token'),
// ],
'query' =>[
'employee_no' => $employee_no,
'name' => $name,
'nid' => $nid,
'dob' => $dob,
'covid_status' => $covid_status,
'vaccine_certificate' => $vaccine_certificate,
'official_email' => $official_email,
'optional_email' => $optional_email,
'official_phone' => $official_phone,
'optional_phone' => $optional_phone,
'designation' => $designation,
'employee_type' => $employee_type,
'role' => $role,
'department' => $department,
'team' => $team,
'grade' => $grade,
'level' => $level,
'avatar' => $avatar,
'present_address' => $present_address,
'permanent_address' => $permanent_address,
'employee_status' => $employee_status,
'employee_invitation_status' => $employee_invitation_status,
]
]);
$result = json_decode((string) $response->getBody(), true);
return $result;
}
catch(\Throwable $e){
return response()->json([
'result' => false,
'message' => 'Something Error!'
]);
}
}
In same code when I comment out $optional_phone and $optional_email , it show success response but when I pass all then it show false result. How I pass an array inside query?

foreach inside foreach and out put first foreach in array

Assume I have an array called (data) and inside my array I have a foreach on products. I need to get each of these product packages inside this (data) array.
Here is what I've tried:
foreach ( $products as $product ) {
$data[] = [
'id' => $product->id,
'packages' => [],
]
foreach ( $product->packageId as $package ) {
$data[]['packages'] = [
'package_id' => $package['id'],
];
}
}
This returns:
- 0 [
id: 977
packages: []
]
- 1 [
packages
package_id: 14
]
- 2 [
packages
package_id: 15
]
I need to return something like this:
- 0 [
id: 977
packages: [
package_id: 14,
package_id: 15
]
]
Update
as #Helioarch and #albus_severus mentioned in they answers that I should create the package array first then include that into the data array
this solution will add the old array of packages in every time the products loops
For Example
product 1 has packages [1,2,3]
product 2 has packages [4,5,6]
in this my case here it will become
product 1 have packages [1,2,3]
product 2 will have packages [1,2,3,4,5,6] <- witch is wrong.
Update 2
Here is my full code
foreach ( $products as $product ) {
$sums = 0;
foreach ( $product->packageId as $package ) {
// Get the total existing inventory
$pckInvSum = $package->pckInventories
->where( 'expiry_date', '<', Carbon::today() )
->where( 'type', 'existing' )->sum( 'amount' );
// Get the total virtual inventory
$pckInvVirtual = $package->pckInventories->where( 'type', 'virtual' )->sum( 'amount' );
// create new array packages to add it to the main json
$packages[] = [
'package_id' => $package['id'],
'package_price' => $package['price'],
'unit_count' => $package['unit_count'],
'existing' => $pckInvSum,
'virtual' => $pckInvVirtual
];
$sums += $package->pckInventories->sum( 'amount' );
}
$data[] = [
'id' => $product->id,
'product_category_id' => $product->product_category_id,
'child_category_id' => $product->child_category_id,
'child_category_two_id' => $product->child_category_two_id,
'child_category_three_id' => $product->child_category_three_id,
'supplier_id' => $product->supplier_id,
'supplier_name' => $product->supplier->contact_name,
'option_category_id' => $product->option_category_id,
'tax_id' => $product->tax_id,
'barcode' => $product->barcode,
'low_price' => $product->low_price,
'image' => $product->image,
'cost' => $product->cost,
'name_ar' => $product->translations[0]->name,
'name_en' => $product->translations[1]->name,
'details_ar' => $product->translations[0]->details,
'details_en' => $product->translations[1]->details,
'sumInv' => $sums,
'campaign' => [
'id' => $product->campaign[0]->id,
'product_id' => $product->campaign[0]->product_id,
'price' => $product->campaign[0]->price,
'purchasesLimits' => $product->campaign[0]->purchasesLimits,
],
'packages' => $packages,
];
You should create the package array first then include that into the data array like so:
foreach ( $products as $product ) {
$packages = [];
foreach ( $product->packageId as $package ) {
$packages[] = [
'package_id' => $package['id'],
];
}
$data[] = [
'id' => $product->id,
'packages ' => $packages,
]
}
EDIT:
Please try again with a revised version of the code you provide below.
foreach ( $products as $product ) {
$sums = 0;
$packages = [];
foreach ( $product->packageId as $package ) {
// Get the total existing inventory
$pckInvSum = $package->pckInventories
->where( 'expiry_date', '<', Carbon::today() )
->where( 'type', 'existing' )->sum( 'amount' );
// Get the total virtual inventory
$pckInvVirtual = $package->pckInventories->where( 'type', 'virtual' )->sum( 'amount' );
// create new array packages to add it to the main json
$packages[] = [
'package_id' => $package['id'],
'package_price' => $package['price'],
'unit_count' => $package['unit_count'],
'existing' => $pckInvSum,
'virtual' => $pckInvVirtual
];
$sums += $package->pckInventories->sum( 'amount' );
}
$data[] = [
'id' => $product->id,
'product_category_id' => $product->product_category_id,
'child_category_id' => $product->child_category_id,
'child_category_two_id' => $product->child_category_two_id,
'child_category_three_id' => $product->child_category_three_id,
'supplier_id' => $product->supplier_id,
'supplier_name' => $product->supplier->contact_name,
'option_category_id' => $product->option_category_id,
'tax_id' => $product->tax_id,
'barcode' => $product->barcode,
'low_price' => $product->low_price,
'image' => $product->image,
'cost' => $product->cost,
'name_ar' => $product->translations[0]->name,
'name_en' => $product->translations[1]->name,
'details_ar' => $product->translations[0]->details,
'details_en' => $product->translations[1]->details,
'sumInv' => $sums,
'campaign' => [
'id' => $product->campaign[0]->id,
'product_id' => $product->campaign[0]->product_id,
'price' => $product->campaign[0]->price,
'purchasesLimits' => $product->campaign[0]->purchasesLimits,
],
'packages' => $packages,
];
}

.NET Core Web Api Loading Nested Entities

I have a db model that looks like:
public CallTrackers()
{
CallTrackerCallerTelns = new HashSet<CallTrackerCallerTelns>();
CallTrackerClients = new HashSet<CallTrackerClients>();
CallTrackerFlwups = new HashSet<CallTrackerFlwups>();
CallTrackerHistory = new HashSet<CallTrackerHistory>();
}
With my GetAll() I am loading everything fine except for CallTrackerClients has 3 nested objects that I can't retrieve:
public CallTrackerClients()
{
CallTrackerClientAdvice = new HashSet<CallTrackerClientAdvice>();
CallTrackerClientOffences = new HashSet<CallTrackerClientOffences>();
CallTrackerClientSureties = new HashSet<CallTrackerClientSureties>();
}
I am trying:
[HttpGet]
public IEnumerable<CallTrackers> GetAll()
{
return _context.CallTrackers
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientAdvice)
.Include(log => log.CallTrackerCallerTelns)
.Include(log => log.CallTrackerFlwups)
.Include(log => log.CallTrackerHistory)
.ToList();
}
The above works but I need to get the Sureties and Offences as well. When I try .ThenInclude(c => c.CallTrackerClientOffences)I get some 'does not contain definition' error.
Any ideas how to get the two remaining collections that are part of CallTrackerClients?
You always have to start from the parent entity.
return _context.CallTrackers
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientAdvice)
// this
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientOffences)
// and this
.Include(log => log.CallTrackerClients)
.ThenInclude(c => c.CallTrackerClientSureties)
.Include(log => log.CallTrackerCallerTelns)
.Include(log => log.CallTrackerFlwups)
.Include(log => log.CallTrackerHistory)
.ToList();

Converting HttpFoundation\Response to an array

My symfony request is returning array with entity object and setstate method.
This is the dump of the array.
array (
0 =>
HealthyLiving\ApiBundle\Entity\User::__set_state(array(
'id' => 1,
'username' => 'admin',
'password' => '123',
'email' => 'batoosay#gmail.com',
'isActive' => false,
)),
)
And here is the code:
public function loginAction()
{
$restresult = $this->getDoctrine()->getRepository('ApiBundle:User')->findAll();
if ($restresult === null) {
return new View("there are no users exist", Response::HTTP_NOT_FOUND);
}
echo '<pre>' . var_export($restresult, true) . '</pre>';die;
return new JsonResponse(
$restresult
);
}
The JsonResponse is empty because of the strange array. How do i convert this array of object to json ?
try to serialize with JMS like this:
$serializer = $this->get('jms_serializer');
return new Response(
$serializer->serialize($restresult, 'json')
);

Laravel 4 + Angular authentication routing

I have an application built using Laravel 4 and AngularJS. Everything is working pretty well except for logout. If I access the route directly (/user/logout), the user is successfully logged out and redirected back to the /login page. However, when I try to link to the laravel logout route in the views, it does not work. I think angular is blocking. I've tried to play around with a few things, but always, the url appears for a split second in the address bar and nothing happens.
From app/views/albums/index.blade.php
<ul>
#if(Auth::check())
<li>My Account</li>
<li>Logout</li>
#endif
</ul>
public/js/app.js
(function() {
var app = angular.module('chp', ['ngRoute', 'projectControllers']);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/albums', {
templateUrl: '/partials/directory.html',
controller: 'ProjectsCtrl'
}).
when('/albums/:slug', {
templateUrl: '/partials/album.html',
controller: 'ProjectDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
$locationProvider.html5Mode(true);
}]);
var projectControllers = angular.module('projectControllers', []);
projectControllers.controller('ProjectsCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('/get_albums', {cache: true}).success(function(albums) {
$scope.projects = albums;
$scope.filters = { };
});
}]);
projectControllers.controller('ProjectDetailCtrl', ['$scope', '$http', '$routeParams', '$sce',
function($scope, $http, $routeParams, $sce) {
$http.get('/get_albums', {cache: true}).success(function(albums) {
$scope.projects = albums;
$scope.filters = { };
for(var i = 0; i < $scope.projects.length; i++) {
if($scope.projects[i].slug === $routeParams.slug) {
$scope.album = $scope.projects[i];
$scope.albumIdx = i;
break;
}
}
$scope.project = albums[$scope.albumIdx];
$scope.showVideo = function(id) {
var videoCode = $(this)[0].song.video;
var listItem = $('li[data-songid="'+id+'"]');
$('li.video').remove();
$(listItem).after('<li class="video"><img src="/img/progress.gif" alt="Loading..."><div class="flex-video">'+videoCode+'</div></li>');
$('li.video').slideDown();
setTimeout(function() {
$('li.video img').hide();
$('li.video .flex-video').fadeIn();
}, 500);
}
$scope.addLyrics = function(id) {
$('#lyricsModal .track-number').html('Add Lyrics - <span style="color: #ccc">' + $(this)[0].song.title + '</span>')
$('#lyricsModal').foundation('reveal', 'open');
$('#add-lyrics-form').prop('action', '/albums/add-lyrics/' + id + '/save');
}
});
}]);
})();
app/routes.php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', array('uses' => 'HomeController#hello', 'as' => 'home'));
Route::get('/login', array('uses' => 'LoginController#index', 'as' => 'login'));
Route::get('get_albums', function() {
return Album::with('songs.lyric', 'artworks', 'series')->get();
});
Route::group(array('before' => 'admin'), function() {
Route::get('/edit-albums', array('uses' => 'AlbumsController#editAlbums', 'as' => 'edit-albums'));
});
Route::group(array('before' => 'auth'), function() {
Route::group(array('prefix' => 'albums'), function() {
Route::get('/', array('uses' => 'AlbumsController#index', 'as' => 'albums-home'));
Route::get('/{slug}', array('uses' => 'AlbumsController#index', 'as' => 'albums-details'));
Route::group(array('before' => 'auth'), function() {
Route::post('/add-lyrics/{id}/save', array('uses' => 'AlbumsController#addLyrics', 'as' => 'add-lyrics'));
});
Route::group(array('before' => 'admin'), function() {
Route::get('/album/{id}/delete', array('uses' => 'AlbumsController#deleteAlbum', 'as' => 'delete-album'));
Route::get('/song/{id}/delete', array('uses' => 'AlbumsController#deleteSong', 'as' => 'delete-song'));
Route::group(array('before' => 'csrf'), function() {
Route::post('/newalbum', array('uses' => 'AlbumsController#saveAlbum', 'as' => 'save-album'));
Route::post('/add-song/{id}/new', array('uses' => 'AlbumsController#saveSong', 'as' => 'save-song'));
Route::post('/update-song/{id}/save', array('uses' => 'AlbumsController#editSong', 'as' => 'update-song'));
Route::post('/update-album/{id}/save', array('uses' => 'AlbumsController#editAlbum', 'as' => 'update-album'));
});
});
});
});
Route::group(array('prefix' => 'forum'), function() {
Route::get('/', array('uses' => 'ForumController#index', 'as' => 'forum-home'));
Route::get('/category/{id}', array('uses' => 'ForumController#category', 'as' => 'forum-category'));
Route::get('/thread/{id}', array('uses' => 'ForumController#thread', 'as' => 'forum-thread'));
Route::group(array('before' => 'admin'), function() {
Route::get('/group/{id}/delete', array('uses' => 'ForumController#deleteGroup', 'as' => 'forum-delete-group'));
Route::get('/category/{id}/delete', array('uses' => 'ForumController#deleteCategory', 'as' => 'forum-delete-category'));
Route::get('/thread/{id}/delete', array('uses' => 'ForumController#deleteThread', 'as' => 'forum-delete-thread'));
Route::group(array('before' => 'csrf'), function() {
Route::post('/category/{id}/new', array('uses' => 'ForumController#storeCategory', 'as' => 'forum-store-category'));
Route::post('/group', array('uses' => 'ForumController#storeGroup', 'as' => 'forum-store-group'));
});
});
Route::group(array('before' => 'auth'), function() {
Route::get('/thread/{id}/new', array('uses' => 'ForumController#newThread', 'as' => 'forum-get-new-thread'));
Route::group(array('before' => 'csrf'), function() {
Route::post('/thread/{id}/new', array('uses' => 'ForumController#storeThread', 'as' => 'forum-store-thread'));
});
});
});
Route::group(array('before' => 'guest'), function() {
Route::get('/user/create', array('uses' => 'UserController#getCreate', 'as' => 'getCreate'));
Route::get('/user/login', array('uses' => 'UserController#getLogin', 'as' => 'getLogin'));
Route::group(array('before' => 'csrf'), function() {
Route::post('/user/create', array('uses' => 'UserController#postCreate', 'as' => 'postCreate'));
Route::post('/user/login', array('uses' => 'UserController#postLogin', 'as' => 'postLogin'));
});
});
Route::group(array('before' => 'auth'), function() {
Route::get('/user/logout', array('uses' => 'UserController#getLogout', 'as' => 'getLogout'));
});
app/controllers/UserController.php
class UserController extends BaseController
{
//gets the view for the register page
public function getCreate()
{
return View::make('user.register');
}
//gets the view for the login page
public function getLogin()
{
return View::make('user.login');
}
public function postCreate()
{
$validate = Validator::make(Input::all(), array(
'username' => 'required|unique:users|min:4',
'pass1' => 'required|min:6',
'pass2' => 'required|same:pass1',
));
if ($validate->fails())
{
return Redirect::route('getCreate')->withErrors($validate)->withInput();
}
else
{
$user = new User();
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('pass1'));
if ($user->save())
{
return Redirect::route('home')->with('success', 'You registed successfully. You can now login.');
}
else
{
return Redirect::route('home')->with('fail', 'An error occured while creating the user. Please try again.');
}
}
}
public function postLogin()
{
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'pass1' => 'required'
));
if($validator->fails())
{
return Redirect::route('login')->withErrors($validator)->withInput();
}
else
{
$remember = (Input::has('remember')) ? true : false;
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('pass1')
), $remember);
if($auth)
{
return Redirect::route('albums-home');
}
else
{
return Redirect::route('login')->with('fail', 'You entered the wrong login credentials, please try again!');
}
}
}
public function getLogout()
{
Auth::logout();
return Redirect::route('login');
}
}
Just create json route for logout and on success change browser url on login. For that define global function logout()
$http.get('route/to/logout').success(
window.location.href = "/login ";
});

Resources