Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x

Laravel

Laravel is a free, open-source PHP web application framework for the development of web applications following the model–view–controller (MVC) architectural pattern. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar. Laravel is regarded as one of the most popular PHP frameworks.

Share tech news, updates, or what's on your mind.

Sign up to Post

I am running composer global require "laravel/installer"

I'm getting the following output

brian@brian-XPS-13:~$ composer global require "laravel/installer"
Changed current directory to /home/brian/.composer
Cannot create cache directory /home/brian/.composer/cache/repo/https---packagist.org/, or directory is not writable. Proceeding without cache
Cannot create cache directory /home/brian/.composer/cache/files/, or directory is not writable. Proceeding without cache
./composer.json is not writable.

Open in new window


I'm running Ubuntu 16.04.
0
Hire Technology Freelancers with Gigs
LVL 11
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

I've been taking on the occasional client, undercharging for my hours to meet market rates, but I just discovered Wordpress and I realized I can have enough output (you know for the average site someone wants to have built) and I can charge extra for custom plugins or Laravel or other solutions that require something more than Wordpress.

After 2018 I would like to start taking on clients - I would like to have the following on my portfolio
-Ecommerce site for local business built with Woocommerce
-Ecommerce site built for another local business built with Woocommerce
-consolidatedutilities.com rewritten in Laravel, possibly with a new design
-effinghamministorage.com possibly redone with wordpress
-pwsmeetup.com - a social media site for people with prader willi syndrome written in Laravel
-umstream.net - a streaming audio site for Umphrey's Mcgee written with Laravel and React

Would listing these sites be a good idea or a bad idea? Should I use Google Adwords? How much do I need to save up for advertising when I build a site advertising services?

I'm going to offer hosting and security. I'm studying Cyber Security and I don't know if I should put that.

I have Schizophrenia and Bipolar and it's a lot harder for me to communicate professionally that it is for most people. Presenting myself well will be a challenge, but I know that my work will be good. I have to work very hard at this, it doesn't come naturally to me, at least not since my diagnosis.

0
I want to create a streaming audio site for a band that allows taping. A site that it will be similar to is this one http://www.panicstream.com/vault/widespread-panic-04192009-orange-beach-al/

How do I create a Streaming Audio site?

I'm not going to mess with Laravel right now, but I want to create a primitive Model View Controller for this site. Can you reference materials on how to build a MVC site?

Thanks
0
I am a Cyber Security major. I've done a lot of programming as a hobbyist, and when I got into Java (and later when I looked at Swift) I felt like I was experiencing some major breakthroughs with Object Oriented Programming and PHP.

I have Crohn's so I didn't even complete the first course which only went up to multidimensional arrays.

So now I need some guidance - do I work out of PHP Patterns Objects and Practice before learning a framework? That book covers Object Oriented Design as well as the concepts.

Should I do that or just move to Laravel and start learning that?

What would be best.

A huge question I have about object oriented frameworks are - can you add functionality that's not built into the framework into your application?

When designing a complex website do you want to use an existing framwork or build your own? If you use an existing one and functionality isn't built in how do you add functionality?
0
Hey, guys!

Here's a snippet from a page called "user.class.php:"

 function updateDevices() {
        global $S;
        global $CN;
        date_default_timezone_set('America/Chicago');
        $maxHistory = date('Y-m-d',strtotime("now - 2 weeks"));
        $R = new xajaxResponse();
        $fitBitCalls = array( '/1/user/-/body/weight/date/'.date('Y-m-d').'/'.$maxHistory.'.json',
        '/1/user/-/body/fat/date/'.date('Y-m-d').'/'.$maxHistory.'.json',
        '/1/user/-/body/log/weight/goal.json',
        '/1/user/-/body/log/fat/goal.json',
        '/1/user/-/activities/steps/date/today/max.json',
        '/1/user/-/activities/calories/date/today/'.$maxHistory.'.json',
        '/1/user/-/activities/distance/date/today/'.$maxHistory.'.json',
        );
        //See if this user any devices that have not been synced.
        $stmt = $CN->prepare("SELECT * 	FROM hraUserDevices  UD INNER JOIN hraUserDeviceTypes UT  ON UD.udtID = UT.udtID  WHERE usrID = ? AND (DATEDIFF(day,udFetchedLastDate,getdate()) IS NULL OR DATEDIFF(day,udFetchedLastDate,getdate()) >=1) AND (udUpdating IS NULL  OR udUpdating !=1 OR DATEDIFF(day,udFetchedLastDate,getdate()) >=2)");
        $stmt->execute(array($S->usrID));
        $devices = $stmt->fetchAll();
        $update = $CN->prepare("UPDATE  hraUserDevices SET udUpdating = ? WHERE udID = ? ");

Open in new window


The question I have is, "What is $CN?"

Obviously, it's a database connection. My problem is that it's not defined anywhere on the page, nor is EVER defined that I can see anywhere in the app.

You do, however, have this at the top of the same page:

	private $cn; // $cn = VARIABLE HOLDING THE DB CONNECTION

	function __construct(PDO $conn) {
		if (!isset($conn))
			throw new Exception('User objects must be passed a PDO Connection object ($this->cn) upon construction');
		$this->cn = $conn;
	}

Open in new window


Is there a convention that I'm missing? $CN is not equivalent to $cn, and yet throughout the entire app you see repeated references to $CN but I can't find anywhere that $CN is actually defined.

Any ideas?
0
Hi I want to update the DB when drag and drop.

I post here the question on SO and you can check all the code.

I will be really appreciated, i'm really stocked.

Link: https://stackoverflow.com/questions/45839623/update-database-when-drag
0
Have integrated social for facebook. It provides only name .But i require birthdate, first and last name, email and phone number.
Same for twitter and google

[token] => XXX
    [id] => 11111111111111
    [nickname] =>
    [name] => Treo Infotech
    [email] =>
    [avatar] => https://graph.facebook.com/v2.10/11111111111111/picture?type=normal
    [user] => Array
        (
            [name] => Treo Infotech
            [id] => 11111111111111
        )

    [firstname] =>
    [lastname] =>
    [avatar_original] => https://graph.facebook.com/v2.10/11111111111111/picture?width=1920
0
I'm trying to figure out what the correct way is to modify a date format before inserting when using Laravel 5.4.

I have:
public function store(){

        $trip = new Trip;
        $trip->tripName = request('tripName');
        $trip->departing = request('departing');
        $trip->returning = request('returning');
        $trip->save();

        return $trip;

        //return redirect('/home');
    }

Open in new window


My database mySQL field in datetime, but the date that's passed in the variable is '07/17/2017 3:20 PM'.  How/where would I update that before insertion?
0
So I've installed Laravel with this tutorial:
https://laravel.com/docs/5.4/installation

I've then installed the authentication module using this tutorial:
https://laravel.com/docs/5.4/authentication

All the pages are there, but when registering it complains about users table not existing in database which is true.  Have I missed a command to execute the migrations file to actually create this table?
0
The following data is returned from my laravel coded controller:

data object
[{"id":1,"name":"View","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27"},{"id":2,"name":"Read","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27"},{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27"},{"id":4,"name":"Update","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27"}]

Open in new window


try object
[{"id":1,"name":"Dashboard","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[{"id":1,"name":"View","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":1,"permission_id_fk":1}},{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":1,"permission_id_fk":3}}]},{"id":2,"name":"Employee","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":2,"permission_id_fk":3}}]},{"id":3,"name":"Report","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[]},{"id":4,"name":"Access Right","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[]}]

Open in new window



In my angularjs controller I have the following line of code:

	$scope.compare = function(a,b){
		$scope.tmp = [];	
		for(var outer in a[0]){
			if(b.length>0){
				for(var inner in b){
					if(b[inner].name === a[0][outer].name){
						$scope.tmp.push({"name":a[0][outer].name,"status":true});
					}
				}
			}else{
				$scope.tmp.push({"name":a[0][outer].name,"status":false});
			}
		}
		return $scope.tmp;
	};

	$scope.init = function(){
		
		$scope.dfperm = [];
		$scope.modperm = [];
		$scope.counter = 0;
		
		$http({
			method: 'GET',
			url: "/api/v1/module/list"
		}).then(function successCallback(response){
			//console.log(response.data);
			//$scope.module = response.data;
			$array = response.data;				
						
			angular.forEach($array, function(outer, key) {			
				if(key==='data'){					
					$scope.dfperm.push(outer);
					//$scope.counter++;
				}
				if(key==='try'){
					angular.forEach(outer, function(outerItem, key){ 
						 var tmp = $scope.compare($scope.dfperm,outerItem.permission);
						 $scope.modperm.push({"name":outerItem.name,"permission":tmp});
					});
				}
			});
		}, function errorCallback(response) {
			console.log('intention error',response.data);
		});
		
	}

Open in new window


What I am attempting to do is to create a new permission object that has the status true or false.

As shown the data object contains a list of default permission.

The try object on the other hand shows that each module has permission. A module can have 0 or more than 1 permission.  

Now i'm trying to reconstruct the information so that each module has equal number of default permission but based on the try object conditioning (permission) is done to set the status either true or false.

However my code above doesn't do so. Rather a module with is set based on the try object conditioning (permission) and others are set with the default permission and status false.

Your help is kindly appreciated.
0
Get your problem seen by more experts
LVL 11
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Hello Experts,

I would like to know if the is a authentication library within Laravel Framwork can support the following requirements? If so, what is it?

any immediate help is highly appreciated.
-regards

> - Application to prevent the re-use of the last 4 passwords.
> - After 5 failed login attempts to the application, further login attempts will remain locked until the affected account is unlocked by an administrator.
> - Password aging set to no more than 90 days, after that they should be reset.
> - Unused accounts should be disabled after one year of inactivity so that they may not be used to access the application.
> - After 5 failed login attempts to the application, further login attempts will be made impossible until the affected account is unlocked by an administrator.
0
I want to know your opinion about site bayt, I want to ask developer framework laravel or other framework, what is the estimated time to realize a site like https://www.bayt.com/fr/
0
Hi everybody.
So I finally decided to start with Laravel. I have followed this tut after having found not clear enough the official doc (since following that I didn't succeed accessing the example website): https://medium.com/@eaimanshoshi/i-am-going-to-write-down-step-by-step-procedure-to-setup-homestead-for-laravel-5-2-17491a423aa

With everything in place, I typed first
git clone https://github.com/laravel/homestead.git Homestead

Open in new window

Then this
cd Homestead
bash init.sh

Open in new window

I have edited the homestead.yaml:
---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: m:/htdocs/LARAVEL_PROJ
      to: /home/vagrant/Code

sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public

databases:
    - homestead

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 50000
#       to: 5000
#     - send: 7777
#       to: 777
#       protocol: udp

Open in new window

A first doubt: homestead.yaml should be .homestead directory but I get it in Homestead directory in my personal directory. Did something went wrong?
And edited the Windows hosts file.
I have created  the ssh key
ssh-keygen -t rsa -C “your_email@example.com”

Open in new window

and I have logged in
homestead ssh

Open in new window

I have launched vagrant (with or without using the shorcut described in the tutorial)
Then I have created a laravel project
composer create-project --prefer-dist laravel/laravel Laravel

Open in new window

The folder Laravel is created ion the virtual machine but not on my hard disk: I can't get it!

Any idea?
0
I am attempting to apply multiple if condition along with the where condition for filtering purpose as below

		$name=$request->input('name');
		$age=$request->input('age');
		$gender=$request->input('gender');
		$company=$request->input('company');
					
		$employees = DB::table('employee')
								->select('id', 'name', 'age', 'gender', 'company')
								->where(function($query) use($name){
										if(!empty($name)){
											$query->where('name','=',$name);
										}
										if(!empty($age)){
											$query->where('age','=',$age);
										}
										if(!empty($gender)){
											$query->where('gender','=',$gender);
										}
										if(!empty($company)){
											$query->where('company','=',$company);
										}
										return $query;
								})
								->get();

Open in new window


However only this condition applies

if(!empty($name)){
											$query->where('name','=',$name);
										}

Open in new window


where else the other conditions are ignored.

Your help is kindly appreciated.
0
Here's the HTML that sets everything in motion:

 <li role="presentation"><a href="#summary" aria-controls="summary" role="tab" data-toggle="tab">Health Summary</a></li>

"#summary" - triggers this function:

    $('a[href="#summary"]').on('click', function(){
        setTimeout(function(){
            HealthSummary.init();
        }, 250);
    });

HealthSummary.init - not sure what that means other than, "initialize." There's another script has this:

var HealthSummary = {
    
    initialized: false,
    
    init: function(){
        var self = this;
        
        if (self.initialized) {
            return true;
        }
        
        $('.health-summary[data-id]').each(function(i){
            
            var $this = $(this),
                id = $this.attr('data-id');
            
            if (id === '') {
                $this.html('<h3 class="text-center">Invalid health summary reference</h3>');
                return true;
            }
            
            $this.html('<h3 class="text-center"><i class="fa fa-refresh fa-spin"></i> &nbsp;Loading Health Summary...<br /><small>(This should only take a few seconds.)</small></h3>');
            
            $.get('/health-summary/' + id, function(resp){
                if (resp.error) {
                    $this.html('<div class="alert alert-danger">' + resp.msg + '</div>');
                    return false;
                }
                
                $this.html(resp.data.html);
   

Open in new window

0
Hi Experts, trying to install a Laravel application, and everything seems to be loading fine as intended, although when i try to install..any link is clicking through to localhost/appname instead of localhost:8888 ..not sure how to update this in laravel app, must be an .htdoc issue maybe...?  I am running on localhost.  Help much appreciated
0
Employee.php

			<tbody>
				<tr ng-repeat="person in employee | orderBy:orderByField:reverseSort">
					<td>{{person.name}}</td>
					<td>{{person.age}}</td>
					<td>{{person.gender}}</td>
					<td>{{person.company}}</td>
					<td>
						 <div class="btn-toolbar" role="toolbar">
							<button class="btn" ng-click="viewEmployee(person.id)"><span class="glyphicon glyphicon-eye-open"></button> 
							<button class="btn" ng-click="editEmployee(person.id)"><span class="glyphicon glyphicon-pencil"></button> 
							<button class="btn" ng-click="deleteEmployee(person.id)"><span class="glyphicon glyphicon-trash"></button>
						 </div>
					</td>
				</tr>
			</tbody>
			<tfoot>
				<tr>  
                    <td align="center" colspan="6">  
                        <div class="pull-right">  
                             <pagination total-items="totalCount" ng-change="pageChanged()" items-per-page="pageSizeSelected" direction-links="true" ng-model="pageIndex" max-size="maxSize" class="pagination" boundary-links="true" rotate="false" num-pages="numPages"></pagination>  
                             <a class="btn btn-primary">Page: {{pageIndex}} / {{numPages}}</a>  
                        </div>  
                     </td>  
                </tr>  
			</tfoot>

Open in new window



EmployeeController.php

	scope.maxSize = 5;
	scope.totalCount = 0;
	scope.pageIndex = 1;
	scope.pageSizeSelected = 5;

        scope.init = function(){
              $http({
			method: 'GET',
			url: "/api/v1/employee/list?pageIndex=" + scope.pageIndex + "&pageSize=" + scope.pageSizeSelected
              }).then(function successCallback(response){
			scope.totalCount = response.data.length; 
                        scope.numPages =  Math.ceil(scope.totalCount / scope.pageSizeSelected);			
		        scope.employee = response.data;
              });
        };

       scope.pageChanged = function(){
		scope.init();
	};

Open in new window


How do I handle pageIndex in laravel? Apart from that I am receiving an error: [orderBy:notarray] when returning in the following manner:

  public function lsAll(){
        $employee = Employee::paginate(5);
	return $employee; 
  }

Open in new window

0
how to get the column value in database for using laravel query?
0
Upon pressing the search button, the values in the form-control disappear.  How do I retain the form control values after triggering the search action.

Employee.php

	<div class="panel panel-default">
		 <div class="panel-heading">Search Employee</div>
		 <div class="panel-body">
			<div class="row">
				<div class="col-md-6">
                    <div class="form-group">
                        <label class="control-label" for="name">Name</label>
                        <input class="form-control" type="text" name="name" id="name" ng-model="employee.name">                    
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="age">Age</label>
                        <input class="form-control" type="age" name="age" id="age" ng-model="employee.age">                    
                    </div>
				</div>
				<div class="col-md-6">
				    <div class="form-group">
                        <label class="control-label" for="gender">Gender</label>
                        <input class="form-control" type="text" name="gender" id="gender" ng-model="employee.gender">                    
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="company">Company</label>
                        <input class="form-control" type="company" name="company" id="company" ng-model="employee.company">                    
      

Open in new window

0
Free Tool: SSL Checker
LVL 11
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

<div class="col-xs-12">
<h2>Listing Employee</h2>
<hr>
<div class="employeeGrid">  
    <table>
        <tr>
            <th><a href="" ng-click="orderByField='name'; reverseSort = !reverseSort">Name</a></th>
            <th><a href="" ng-click="orderByField='age'; reverseSort = !reverseSort">Age</a></th>
            <th><a href="" ng-click="orderByField='gender'; reverseSort = !reverseSort">Gender</a></th>
            <th><a href="" ng-click="orderByField='company'; reverseSort = !reverseSort">Company</a></th>
            <th>Action</th>
        </tr>
        <tr ng-repeat="person in employee | orderBy:orderByField:reverseSort"">
            <td>{{person.name}}</td>
            <td>{{person.age}}</td>
            <td>{{person.gender}}</td>
            <td>{{person.company}}</td>
            <td>
                 <button class="btn" ng-click="viewEmployee(person.id)"><span class="glyphicon glyphicon-eye-open"></button> 
                 <button class="btn" ng-click="editEmployee(person.id)"><span class="glyphicon glyphicon-pencil"></button> 
                 <button class="btn" ng-click="deleteEmployee(person.id)"><span class="glyphicon glyphicon-trash"></button>
            </td>
        </tr>
    </table>        
</div>

Open in new window


EmployeeController.js

scope = $scope;

scope.employee = [];

scope.$on('$stateChangeSuccess', function () {
    scope.init();   
});

scope.init = function(){
    $http({
        method: 'GET',
        url: '/api/v1/employee/list'
    }).then(function successCallback(response){
        scope.employee = response.data;
    });
}

scope.editEmployee = function(val){

    empScope = $scope;

    $uibModal.open({
        animation: false,
        templateUrl: '../assets/templates/modal/employee/updateEmployee.php',
        controller: 'UpdateEmployeeController',
        size: '',
        backdrop: 'static',
        resolve: { empId: function () { return val; } }
    }).result.catch(function(res) {       
          if (!(res === 'cancel' || res === 'escape key press')) {
            throw res;
          }
    });
};

Open in new window


UpdateEmployeeController.js

scope = $scope;

scope.employee = [];

$http({
       method: 'GET',
       url: '/api/v1/employee/get/' + scope.$resolve.empId
}).then(function successCallback(response){
       scope.employee = response.data;
});

scope.updateEmployee = function(){

       $http({
            method: 'POST',
            url: '/api/v1/employee/update/' + scope.$resolve.empId,
            data: {
                name:scope.employee.name,
                age:scope.employee.age,
                gender:scope.employee.gender,
                company:scope.employee.company
            }
       }).then(function successCallback(response){
            //console.log(response.data);                       
       }, function errorCallback(response) {
            console.log(response.data);
       });

       //scope.$dismiss('cancel');
}

Open in new window


EmployeeController.php

public function lsAll(){
    $employee = Employee::all();
    return $employee;
}

public function getOne($id){
    $employee = Employee::find($id);
    return $employee;
}

public function update(Request $request, $id){
    $employee = Employee::findOrFail($id);      

    $name=$request->input('name');
    $age=$request->input('age');
    $gender=$request->input('gender');
    $company=$request->input('company');

    $employee->name = $name;
    $employee->age = $age;
    $employee->gender = $gender;
    $employee->company = $company;

    if($employee->save()){ 
        return response()->json(['response' => 'The employee record is updated successful']);
    }else{
        return response()->json(['response' => 'Failed to update the employee record']);
    }
}

Open in new window



QUESTION

How do I parse an event from UpdateEmployeeController to EmployeeController during an edit action and render (reload) a specific record with the updated data from database.
0
I did a method to filter the results, I want for example looking for a hotel in a city and whose price and between 0 and 49, I have 4 checkbox 0-49, 50-99,100-149,150-200 I want If I click on the first it gives me the names of the hotels whose city given in query and the price that is in the value of checkbox

For example:

If I look for the city Casablanca, it gives me the name of the hotels that have in Casablanca and when I click on the checkbox 0-49 it gives me the hotels that have in Casablanca and whose price is between 0 and 49 and so on For other checkboxes when I click on the first checkbox that contains the value 0-49 and the second one that contains the value 50-99, it gives me the hotels that have in Casablanca and whose price is between 0 and 49 and 50 -99 and so on

The method works very well, the problem is in pagination, when I click on a single checkbox it gives the exact page number and the number of element to display in the pages is 25

 $ Perpage = 25;

I have made $ product to display the names of hotels and $ afica to calculate the total number of results, because the method "totalHits ()" only works with the get () method,


$ Books = $ product [0]; // this line stores the first results that is to say when I have a single checkbox but when I click on several checkbox it enters the loop for:

 for($i=1;$i<count($product);$i++){
                    
            $collection  = new Collection();
            $collection2 = new 

Open in new window

0
Hi, I want to select all hotels where minrate between 0 and 49 it marche perfectly , but when i want to select all hotels where minrate between 0-49 and 50-99 It is you to say when it enters the loop "for" it return this error

ErrorException in Macroable.php line 74:
Method appends does not exist. (View: C:\xampp\htdocs\elasticsearch\resources\views\presult.blade.php) (View: C:\xampp\htdocs\elasticsearch\resources\views\presult.blade.php)

Function Laravel
public function pricefilter(Request $request)
    {
         $query = Input::get('query', false);
       $brans = request()->priceFilter;
         $books = new Collection(); 
if(!empty($brans))
        { 
            $product = "";

foreach($brans as $data){
               $minMax = explode("-",$data);
              
            
                $product[] = Afica::search()
                    ->multiMatch(['name','city_hotel'], $query, ['fuzziness' => 'AUTO'])
                    ->filter()
                    ->range('minrate',['from'=>$minMax[0],'to'=>$minMax[1]])
                    ->paginate(26)
                    ->appends('priceFilter' , request('priceFilter'));
            
            
                
     
         }
          $books= $product[0];
          for($i=1;$i<count($product);$i++){
              $books=$books->union($product[$i]);
        

          }
         }
        else 
        {
               $books = Afica::search()
            ->paginate(26);
   
        

Open in new window

0
Hi,

I am using PHP Laravel. I am storing the count of items in a table.  When a customer purchases an item, we first look at the count of items available, then there are some other related DB operations that are done and there is a logic to reduce the item count and store it back.

However, if 2 customers purchase the item at the same time, there is a race condition and the count gets reduced only by 1. There is a lot of other backend logic and DB operations that happen before the value is updated in the table.

How can I manage the race condition either at the DB level, so that the table is locked for reading till the previous transaction is completed or at the code level, the code is considered as a critical section and locked till the complete code for one purchase goes through.

Help will be appreciated.
0
I'm creating pagination manually for results using Eloquent ORM. The pagination works fine except it's defaulting to display only back and next buttons (simplePaginate()) rather than back, next and page number links.

Here's how I'm generating the pagination;

$data = new \Illuminate\Pagination\Paginator($allRecipes, $perPage, $page, ["path" => "recipes"]);

Open in new window


Is there a way I can ask for the pagination to not be the equivalent of calling 'simplePaginate()'?
0
I'm using Laravel and the Eloquent ORM, I seem to be having a strange issue not being able to call static methods on an eloquent object. I keep getting the error below;


BadMethodCallException in Builder.php line 2405:
Call to undefined method Illuminate\Database\Query\Builder::searchRecipes()

The object I'm trying to call looks like this;

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Class Recipe
 * @package App\Models
 * @property int $id
 * @property string $title
 * @property string $description
 * @property string $web_url
 * @property int $servings
 * @property string $photo_url
 * @property string $thumbnail_url
 * @property boolean $is_published
 * @property string $chef_name
 * @property string $chef_url
 * @property int $cook_time
 * @property int $prep_time
 * @property string $source_url
 * @property boolean $vegetarian
 * @property boolean $vegan
 * @property boolean $dairy_free
 * @property boolean $gluten_free
 * @property boolean $very_healthy
 * @property int $ww_points
 * @property boolean $cheap
 * @property int $category_id
 * @property int $course_id
 * @property string $created_at
 * @property string $updated_at
 */
class Recipe extends Model
{
    protected $table = 'recipe';

    public static function searchRecipes($criteria)
    {
        if (!empty($criteria->title) || $criteria->categoryId > 0) {
            $query = self::where('title', 'like', "%$criteria->title%");
            if 

Open in new window

0

Laravel

Laravel is a free, open-source PHP web application framework for the development of web applications following the model–view–controller (MVC) architectural pattern. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar. Laravel is regarded as one of the most popular PHP frameworks.

Top Experts In
Laravel
<
Monthly
>