Sunday, April 16, 2017

Laravel Calculate AVG of a related column

I am trying to calculate average ratings of a related column. The relationship (1->many) is in between Merchant & ClientFeedbackReviews Models.

Merchant Model

[Merchant Model]
::::::::::::::::::::::::::::

public function clientFeedbacks() {
    return $this->hasMany('App\ClientFeedbackReviews'); //, 'merchant_id', 'id');

ClientFeedbackReviews

 ::::::::::::::::::::::::::::::::::::::: 

class ClientFeedbackReviews extends Model {

protected $table = 'client_feedback_merchants';
public function forMerchant() {
    return $this->belongsTo('App\Merchant', 'merchant_id', 'id');
}

public function byClient() {
    return $this->belongsTo('App\Clients', 'client_id', 'id');
}
:::::::::::::::::::::::::::::::::::::

I need to get average ratings of all the merchant (as a PART of a query where I am calculating results-the merchants according to nearby distances, given location or a using search string depending upon the Request Data)

I have tried almost everything I found on internet but couldn't able to get 'average_ratings' key-value in results.

Here is one the many solutions that I have tried and pasting here as an example

 /////// query continued //////////

 $getMerchantQuery = $getMerchantQuery->with(['clientFeedbacks' => function($query) {

            $query->select(DB::raw('AVG( stars) AS average_rating'));
        }]);

 /////// query continued //////////

and this the what I am getting ALWAYS - empty array for client_feedbacks whereas I want the average_rating right there.

  {
"id": 1,
"user_id": 2,
"company_name": "Best Salon",
"primary_contact": "111111111",
"company_st_address": "Office # 62",
"company_location": "Abc",
"company_city": null,
"company_state": null,
"company_country": null,
"company_zip": null,
"company_lat": "27.9506",
"company_long": "82.4572",
"logo_image": "449cbdf0-12ba-11e7-bc65-b7fa1731e4d5.jpeg",
"is_fav_by_client_count": 3,
"client_feedbacks_count": 1,
"user_details": {
  "id": 2,
  "email": "client@lir.com"
},
"client_feedbacks": []

}

What are the options do we have to calculate avg of a related table ?

============ EDIT

However this returns results but not sure how to get the AVERAGE in client_feedbacks key.

      $getMerchantQuery = $getMerchantQuery->with('clientFeedbacks');

as

{
"id": 1,
"user_id": 2,
"company_name": "Best Salon",
"primary_contact": "111111111",
"company_st_address": "Office # 62",
"company_location": "abc",
"company_city": null,
"company_state": null,
"company_country": null,
"company_zip": null,
"company_lat": "27.9506",
"company_long": "82.4572",
"logo_image": "449cbdf0-12ba-11e7-bc65-b7fa1731e4d5.jpeg",
"is_fav_by_client_count": 3,
"client_feedbacks_count": 1,
"user_details": {
  "id": 2,
  "email": "client@lbb.com"
},
"client_feedbacks": [
  {
    "id": 1,
    "client_id": 1,
    "merchant_id": 1,
    "stars": 4,
    "review_notes": "good client",
    "created_at": null,
    "updated_at": null
  }
]

}



via Zeshan

Use Eloquent Model from another table

I'm new into Laravel.

I've created a Model and Controller without a table. "Api.php" and "ApiController.php".

I want to use data from table "sites". So far my model has "protected $table = 'sites';"

Is this enough? How can I test if it get data from it?

Thank you



via altos

Laravel 5 Search in Multi attributes

I`m new to the laravel 5.4 and i need to create a multi attribute search.i can only do the search for a single attribute.but i cannot find out the right way to do so.

here is the search field i want. enter image description here

Here is the view related to it.

 <div class="form-group">
        <!-- <label>Select Your Institute</label> -->
        <label>Search By</label>
<select name="institute" id="institute">
  <option selected="selected" value="Trainee Id">Trainee Id</option>
    <option value="Trainee Name">Trainee Name</option>
  <label for="Search">Name</label>
</select>

<form action="search" method="post" class="form-inline">


       <input type="text" name="search" /><br>
       <input type="hidden" value="" name="_token" />
       <input type="submit" name="submit" value="Search">
       </form>


</div>

Here is the Controller which i need the modification for above view specially in drop down.

public function search_code(Request $request){
        $query = $request->search;
        $customers = DB::table('registerdetails')->where('id', 'LIKE',"%$query%")->get();
         return view('registeredusers.index')->with('customers',$customers);

        }

Can anyone suggest me the controller which i select from the drop down?



via Dasun

Combie domain with active record

I use yii2 and find that it's active record is very convenient.

But sometimes I find that we always put logic functions in active record which I think should belongs to domain.

And I have looked up some books, most of them suggest using data mapper to mapping database record to domain.

Although it is a good way to split domain and data, I don't want to waste active record feature from yii2.

I think we can make a domain extend from active record so that the database operations will in domain's parent class active record, and business logic operations will in domain:

class UserModel extends ActiveRecord{
      // do database operations
}

class UserDomain extends UserModel{
    // do domain's logic
}

I don't know is this design great? Please tell me your suggests.



via Jack

Laravel 5 Search in Multi attributes

I`m new to the laravel 5.4 and i need to create a multi attribute search.i can only do the search for a single attribute.but i cannot find out the right way to do so.

here is the search field i want. enter image description here

Here is the view related to it.

 <div class="form-group">
        <!-- <label>Select Your Institute</label> -->
        <label>Search By</label>
<select name="institute" id="institute">
  <option selected="selected" value="Trainee Id">Trainee Id</option>
    <option value="Trainee Name">Trainee Name</option>
  <label for="Search">Name</label>
</select>

<form action="search" method="post" class="form-inline">


       <input type="text" name="search" /><br>
       <input type="hidden" value="" name="_token" />
       <input type="submit" name="submit" value="Search">
       </form>


</div>

Here is the Controller which i need the modification for above view specially in drop down.

public function search_code(Request $request){
        $query = $request->search;
        $customers = DB::table('registerdetails')->where('id', 'LIKE',"%$query%")->get();
         return view('registeredusers.index')->with('customers',$customers);

        }

Can anyone suggest me the controller which i select from the drop down?



via Dasun

How can to fix Interface "App\Illuminate\Contracts\Auth\Aunthenticatable' not found" in laravel

this my code :

use Illuminate\Database\Eloquent\Model;

use Illuminate\Auth\Authenticatable;

class Admin extends Model implements Illuminate\Contracts\Auth\Aunthenticatable { use Authenticatable;

}

but it said "App\Illuminate\Contracts\Auth\Aunthenticatable not found"



via user3065621

JWT with AngularJS not storing token

My token is currently being retrieved on the Laravel end. I used Postman to verify this. I want to decrypt and store my token into local storage for a session with the user, but not sure how to go about this. I want to just put it in the login function which is currently doing the following:

$scope.login = function() {
  $http.post('http://thesis-app.dev/login', $scope.user, {headers: {'X-
   Requested-With': 'XMLHttpRequest'}}).success(function(response) {
  console.log($scope.user);
   })

  .success(function(){
   console.log("user logged in!");
   console.log(response)

   })
   .error(function() {
   console.log("their was an error");
   console.log(response);

   });
 }



via Meaghan Florence

(laravel) Two ORDER BY clauses and a LIMIT

This is some sorting:

  1. I want to list today's 20 best posts based on "views".
  2. then, sort it based on "created_at".

How to do it?

Heres my current code (which doesnt work):

$post = 
Posts::orderBy('views', 'desc')
->orderBy('created_at', 'desc')
->whereRaw('created_at >= NOW() - INTERVAL 1 DAY')
->limit(20)->get();



via dobieme

What does this PHP syntax mean in layman's term?

I'm trying to understand a syntax and I would greatly appreciate if someone can tell what this means in layman's term:

Route::get('/member-profile-form', ['as' => 'newmemberprofileform', 'uses' => 'User\MemberProfileFormController@showForm']);

Particularly the one that says 'as'... Thanks!



via Rodney Zanoria

[SOLVED]How do I input custom variables in User::create() in Laravel?

$user = User::create(request(['name', 'email', 'password']));

In the above code, what syntax do I need to use to replace the request()->password variable with a custom $password variable?


via Simon Suh

How do I log in a user in Laravel?

I'm practicing manual authentication in Laravel for learning purposes, following along laracasts.com and reading the manual user authentication related documentation here - https://laravel.com/docs/5.4/authentication#authenticating-users

My login controller code is as follows:

public function loginSubmit() {
  $email = request('email');
  $password = request('password');

  if (Auth::attempt(['email' => $email, 'password' => $password])) {
    return 'logged in';
  } else {
    return 'not logged in';
  }

Albeit the password not being hashed, I am using the Auth::attempt with the correct email and password information but am not able to return 'logged in'. How can I get the login to work with Auth::attempt ?



via Simon Suh

How do I enter password into database as hashed in Laravel?

$this->validate(request(), [
    'name' => 'required',
    'email' => 'required|email',
    'password' => 'required|confirmed'
  ]);

  $user = User::create(request(['name', 'email', 'password']));

I have the above code in my current controller to receive data from the user registration form and it properly enters the user into the Users table in the Database. However, the password is not hashed, and I am wondering what is the correct method of storing hashed passwords in Laravel? (and what is the official hash to use in Laravel?) I'm following along a Laracasts.com tutorial.



via Simon Suh

Return class variable of a Laravel Model in JSON

I have the following model class

class MyModel extends Model {
    public $some_variable; // I don't want to store this in the database
    protected $fillable = ['column1', 'column2'];

In the controller:

$model = MyModel::find(2);
$model->some_variable = "some value"; // Dynamically calculated each time
return response()->json($model);

The response contains all the columns from MyModel but does not contain $some_variable. Why could this be happening? Are class variables transient by default?



via Gaurav Bhor

How to show result as nested categories in Laravel 5.2

Intoduction:
Often the programmer wants to build nested product categories so that he can customize the type of products he has and also for easy modification it.

Idea:
first: i have 5 migrations about categories tables

// migration: 1
Schema::create('products_categories_1', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
});

// migration: 2
Schema::create('products_categories_2', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('related_id')->unsigned();
    $table->string('name');
    .....
});

// migration 3, 4 and 5 is the same with 2

migrations view example taken from database
products_categories_1 table products_categories_2 table

To be aware, I have completed the system of adding, modifying and deleting any of these categories.

second: i have products migration

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('category_table_number');
    $table->integer('category_id');
    ..... 
});

products table

by applying this code

Product::users_roles()
    ->where('category_table_number', $category_table_number)
    ->where('category_id', $category_id)
    ->lists('id');

Issue:
With this previous code, the product with the direct rating is obtained only, but I want to get all products with nested categories

example:

Product::users_roles()
    ->where('category_table_number', 1)
    ->where('category_id', 4)
    ->lists('id');

// Result: array('11') (from product table image)

product table products_categories_1 table

// but i want to appear all products with nested categories like
// Result: array('11', '1') (from product table image)

products table produts_categories_2 table

I wish:
I could find a solution to that problem or if I had a better idea of making overlapping classifications, please see me it


Thanks for any help



via Ahmed Sk

how to create an array in foreach loop?

I want to create an array like this for telegram markup:

['بازگشت👆'],
['🛫 از آتن'],

I am using a foreach for this array like this:

$destination = array("بازگشت👆,");
            foreach ($getto->getCity as $key => $todes) 
            {
                $destination[]=array( "'🛬 به "."$todes->city" ." (از " . "$todes->price" ." تومان)'"); 
            }

bot it gave me an array with keys.how can I create an array like that telegram accept?



via mrmrn

Retriving data by other field than id in has Many relations

I have a has many relation between models: post and category in laravel application. I've defined these relations as:

public function category(){

        return $this->belongsTo('artSite\category');

    }

 public function posts(){

        return $this->hasMany('artSite\post');
    }

Now I'm trying retrieve posts belonging to the particular category which are derived in http request:

Route::get('posts/categories/{categoryName}','postsViewController@showPostGivenCategory')

Below I show my controller function(It does works fine!):

 public function showPostGivenCategory($categoryName){



     $category = category::where('category_name','=',$categoryName)-first();
     $posts = category::find($category->id)->posts;
     return view('pages.homePage')->with('categories',$categories)with('posts',$posts);

 }   

In this solution I'm creating 2 queries. Is any possible way to create 1 quuery to retrieve posts of particular category in has many relation?

Something like that doesn't work:

$posts = category::where('category_name','=',$categoryName)->posts;

Could someone help me with this problem? I would be very grateful, greetings.



via Krzysztof Michalski

How to show 2 tables data in 1 view using laravel?

There is two tables (one is Users and second is Branches). I want to show the Branch with its Branch Admin Name.And the branch Admin info is save in users table. There is an error When i am trying to show the data of Two table in one view. Tell me How i manage this issue.

View:

<div class="branches col-xs-12 col-sm-12 col-md-9 col-lg-9">
    <input type="text" class="pull-right form-control search" placeholder="Search">

    <div class="spaces"></div>

    <table class="table table-bordered">
        <thead>
        <tr>
            <th>
                BranchName
            </th>
            <th>
                BranchAdmin
            </th>
            <th>
                Email
            </th>
            <th>
                Contact
            </th>
            <th>
                Location
            </th>
            <th>
                Action
            </th>
        </tr>
        </thead>
        <tbody>
        @foreach($branch as $brnch)
            <tr class="branchies-row">
                <td>
                    
                </td>
                @foreach($user as $users)
                    <td>
                        
                    </td>
                @endforeach
                <td>
                    
                </td>
                <td>
                    
                </td>
                <td>
                    
                </td>


                <td>
                    <a data-id="" class="delete-branch">Delete</a> /
                    <a href="/branch/edit/">Edit </a>
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

Controller:

public function getBranchinfo(){
    $user = User::where('type', '=', 'BranchAdmin');
    $branch = Branch::all();
    return view('Branch.branchinfo')->with('branch',$branch)->with('user', $user);
}

Model:

public function branch(){
    return $this->hasOne('App\Branch', 'user_id', 'id');
}



via Haider

Change default laravel email template theme sent to gmail or hotmail

This is default email generated and sent by laravel using smtp , and i want to change this default template like adding some pictures,url... how can i do that? thanks

image



via Ilham Guezzoula

Where is Laravel's password reset email?

In Laravel Framework 5.4.18 I just ran php artisan make:auth

When I request to reset my password, I get an email that says

(...)

You are receiving this email because we received a password reset request for your account

(...)

Where is the file where it is specified to say that? I want to change it completely.

From already thank you very much.



via emi

Select from 3 tables with 2 foreign keys

I have a table service which contains <PK> id and <FK> plate_number.

Then I have a table vehicles, which contains <PK> plate_number and other not important columns.

Next table is a binding table part_fix containing <FK> service_id and <FK> part_id.

Last one is part with columns id, name, `price.

I am using Laravel query builder but thats not so important now, just in case someone knows how to use it, a solution in query builder would be better for me.

I want to select from table service where I want to show in a table <PK> id, <PK> plate_number, and using the binding table, I want to assign parts for each service. I have the binding table because there was many to many relationship (one repair/service can have many parts, and also one part can be used in many repairs in autoshop).

I hope I explained this good enough, if not please ask.



via Ady96

enum values from mysql table

I have a enum column in my table and I am trying to get out the values I have set in the table in a drop down. So first I have written this query to get the column_type and column_name

"SELECT `COLUMN_NAME`,`DATA_TYPE`,`COLUMN_TYPE` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='devsbh' AND `TABLE_NAME`='modules' AND `COLUMN_NAME` NOT IN ('created_at', 'updated_at')"

then I do this to get out the enum values like so

<?php 
   $regex = "/'(.*?)'/";
   preg_match_all( $regex , $modules->COLUMN_TYPE , $enum_array );
   $enum_fields = $enum_array[1];
?>

and I display like so

PS:Using laravel's blade template engine.

{!! Form::select($modules->COLUMN_NAME,$enum_fields) !!}

Everything is correct up until here. When I try to store it tries too save as for Y => 0 and for N => 1. How can I get the key => value same as enum value?

the values of $enum_fields as per the console is [0]=>Y , [1]=>N.



via this.Believer

Error while using yield in Form:text value

1) Making CRUD so wanted to use yield in value in Form:text to load the values

{!! Form::Text('employeeName_txt',
'@yield('editEmployeeName')',
array('class' => 'form-control','placeholder'=>'Employee Name')) !!}

Getting error

FatalErrorException in 2168be22f5078758fb418696bf6815fc3ab642a4.php line 59:
syntax error, unexpected 'editEmployeeName' (T_STRING)

Can anyone please help what is wrong in this & also 2) Which is the best method for CRUD

  • Creating Edit page differently & extending it with create page and yield or section the values

  • Or in create page only, with the use of if else condition do the coding eg: if route name contains edit then method= put ,delete button show etc.



via Sumeet

Laravel-echo-server: how to listen to user leaving a channel

I've been fiddling a lot lately with Laravel Echo and Laravel Echo Server, a socket.io server implementation for Laravel Echo.

There's not much on the web, and I'm probably missing some point..

I can see from the cli of laravel-echo-server when a user joins or leaves a channel (presence channel in my case). I have a Laravel Event that performs some DB operations that I want to fire when a user leaves a presence channel. How can I achieve this?

Thanks



via Edo San

Larvel DataBase Connexion

I install laravel on Ampps (windows 10) with .

it works.

But Now I want connect to mysql.

I create a 'blog' DB and change these two files: .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD='mysql'

and /config/database.php :

  'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'blog'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', 'mysql'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

but still i get this when i want to migrate :



via khalil jridi

XAMPP (Apache) Crashes after adding mongodb.so to php.ini

I'm trying to use MongoDB with Laravel for the first time with XAMPP (OSX) and the Jenssegers/mongodb plugin: - https://github.com/jenssegers/laravel-mongodb

I have added the following line to the php.ini file. extension="/usr/local/opt/php56-mongodb/mongodb.so"

Afterwards apache is unable to run.

error log shows the following:


[Sun Apr 16 19:55:16.004447 2017] [ssl:warn] [pid 64283] AH01906: www.example.com:443:0 server certificate is a CA certificate (BasicConstraints: CA == TRUE !?) [Sun Apr 16 19:55:16.004729 2017] [ssl:warn] [pid 64283] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Sun Apr 16 19:55:17.002106 2017] [ssl:warn] [pid 64284] AH01906: www.example.com:443:0 server certificate is a CA certificate (BasicConstraints: CA == TRUE !?) [Sun Apr 16 19:55:17.002248 2017] [ssl:warn] [pid 64284] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name


This question has been asked a couple of time: https://github.com/mongodb/mongo-php-driver/issues/247

Using the --with-mongodb-sasl=no argument might solve it? As a total newbie, I have no clue how to use this though.. Can anyone help me with this problem??

php version: 5.6.3 mongodb version: 1.2.8 Laravel version: 5.4 Jenssegers/mongodb extension version: 3.2



via Martijn Boekema

Add branch before create branch Admin using laravel

I am trying to do that when i add a new branch, I want to create an Admin for this branch, but in this the branch form have an input field of branch Admin when i am adding a new branch it does not create a branch because the Admin input field is empty, because there is no Admin available. And i want to do that whether it is or not the Admin is existing or the branch is existing, when i am adding/creating the branch or branch-Admin it not give the validation error.

Add-Branch View:

    <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
    <form class="form-horizontal branch-form" action="/add/branch" method="post">
        <div class="form-group">
            <label class="col-sm-3 control-label">Company</label>
            <div class="col-sm-9">
                <select  class="form-control" name="company_id">
                    <option value="">Select</option>
                    @foreach($company as $compny)
                        <option value=""></option>
                    @endforeach
                </select>
                @if($errors->has('company_id'))
                    
                @endif
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">BranchAdmin</label>
            <div class="col-sm-9">
                <select  class="form-control" name="user_id">
                    <option value="">Select</option>

                        @foreach($user as $usr)
                            <option value=""></option>
                        @endforeach
                </select>
                @if($errors->has('user_id'))
                    
                @endif
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">Branch-Name</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" name="name" placeholder="Name">
                @if($errors->has('name'))
                    
                @endif
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">Email</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" name="email" placeholder="Email">
                @if($errors->has('email'))
                    
                @endif
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">Address</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" name="address" placeholder="Location">
                @if($errors->has('address'))
                    
                @endif
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">Contact</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" name="contact" placeholder="Contact">
                @if($errors->has('contact'))
                    
                @endif
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">Open-Hours</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" name="open_hours" placeholder="Shop-Open-Hours">
                @if($errors->has('open_hours'))
                    
                @endif
            </div>
        </div>

            @if(Session::has('message'))
                <div class="form-group">
                    <label class="col-sm-3 control-label"></label>
                    <div class="col-sm-9">
                        <div class="alert alert-info" role="alert"></div>
                    </div>
                </div>
            @endif

        <div class="form-group">
            <label class="col-sm-3 control-label"></label>
            <div class="col-sm-9">
                <button type="submit" value="add branch" class="btn btn-default">Submit</button>
            </div>
        </div>
        
    </form>
    </div>

Branch-Admin View:

<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">

<form class="form-horizontal register-form" action="/make/branch/admin" method="POST">
    <div class="form-group">
        <label class="col-sm-3 control-label">Name</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" name="name" placeholder="Name">
            @if($errors->has('name'))
                
            @endif
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-3 control-label">Email</label>
        <div class="col-sm-9">
            <input type="email" class="form-control" name="email" placeholder="Email">
            @if($errors->has('email'))
                
            @endif
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-3 control-label">Password</label>
        <div class="col-sm-9">
            <input type="password" class="form-control" name="password" placeholder="Password">
            @if($errors->has('password'))
                
            @endif
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-3 control-label">Contact</label>
        <div class="col-sm-9">
            <input class="form-control" name="phone" placeholder="Contact number">
            @if($errors->has('phone'))
                
            @endif
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-3 control-label">CNIC</label>
        <div class="col-sm-9">
            <input type="text" id='cnic' class="form-control" name="cnic" placeholder="CNIC">
            @if($errors->has('cnic'))
                
            @endif
        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-3 control-label">Address</label>
        <div class="col-sm-9">
            <textarea class="form-control" type="text" name="address" placeholder="Address" rows="5"></textarea>
            @if($errors->has('address'))
                
            @endif
        </div>
    </div>
    @if(Session::has('message'))
        <div class="form-group">
            <label class="col-sm-3 control-label"></label>
            <div class="col-sm-9">
                <div class="alert alert-info" role="alert"></div>
            </div>
        </div>
    @endif


    <div class="form-group">
        <label class="col-sm-3 control-label"></label>
        <div class="col-sm-9">
            <button type="submit" value="Register" class="btn btn-default">Register</button>
        </div>
    </div>
    
</form>
</div>

Branch Controller:

public function savebranchinfo(Request $request){
        $validator = Validator::make($request->all(),[
            'company_id' => 'required',
            'user_id'=>'required',
            'name' => 'required|min:5',
            'email' =>'required|unique:branch,email',
            'address' =>'required',
            'contact' =>'required|max:11|unique:users,contact',
            'open_hours' =>'required',
        ]);
        if($validator->passes()){
            $branch = new Branch();
            $branch->company_id = $request->company_id;
            $branch->user_id = $request->user_id;
            /*dd($request->company_id);*/
            $branch->branch_name = $request->name;
            $branch->email = $request->email;
            $branch->address = $request->address;
            $branch->contact = $request->contact;
            $branch->open_hours = $request->open_hours;
            if($branch->save() || Auth::user()->type === 'BranchAdmin'){
                $request->session()->flash('message','Successfully save!!');
                return redirect('/add/branch');
        }else{
                return redirect('/add/branch')->withErrors($validator)->withInput();
        }
    }

BranchAdmin Controller:

public function saveadmininfo(Request $request){
        $validator = Validator::make($request->all(), [
            'name' => 'required|min:4',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:4|',
            'phone' => 'required',
            'cnic' => 'required|unique:users,CNIC|min:15|max:15',
            'address' => 'required'
        ]);
        if ($validator->passes()) {

            $user = new User();
            $user->name = $request->name;
            $user->email = $request->email;
            $user->password =bcrypt($request->password);
            $user->contact = $request->phone;
            $user->CNIC = $request->cnic;
            $user->address = $request->address;
            $user->verified = true;
            $user->verification_token = '';
            $user->type = 'BranchAdmin';
            if ($user->save()) {
                $request->session()->flash('message', 'Successfully registered Branch Admin!!');
                return redirect('/make/branch/admin');
            }
        }else{
            return redirect('/make/branch/admin')->withErrors($validator)->withInput();
        }
    }
}

Model:

public function branch(){
        return $this->hasOne('App\Branch', 'user_id', 'id');
    }



via Haider

Laravel multiple occurrences of relation

I'm building an api for a clothing store with Laravel 5.4 and I have this situation. I have a Rack that has clothes on it. But the same piece can occur multiple times on the rack.

rack
-id
-description
product
-id
-description
product_rack
-id
-rack_id
-product_id

I have a many to many relation because a product can occur on many racks and a rack has multiple products. However I'am not sure how I can attach a product multiple times to a rack.

Like for instance Rack with id of 1 has 2 times product 5 and 1 time product 3.

I can use the attach() function but if I detach() it releases all products from the rack instead of one.



via job vink

Laravel clean way to handle data after a webhook

So I got webhooks working and I also got a source polling page where ajax checks the status of the payment.

But now I don't know how to handle the data in a clean way. I could post the data from a view to a controller but I don't like it that way. I could also change the webhooks to return to a route, but I don't know if that will mess stripe up, since it wont get a http 200 (ok) status.

So what is a clean way to deal with a customer after he paid? Where should I redirect him to and how can I make sure my controller gets the user data after he paid.



via Jozzy91

UniSharp/Laravel Filemanager and TinyMCE integration

I have done a fresh installation of laravel project just to try out tinyMCE with UniSharp filemanager. I have done the UniSharp + tinyMCE instalation following the guide on the github https://github.com/UniSharp/laravel-filemanager.

The WYSIWYG editor is showing up correctly in the browser and I am also able to click the image upload button. However, I get the screen showing Objec not found error.

Object Not Found

My code for the set up looks like this. Original!

<script src="//cdn.tinymce.com/4/tinymce.min.js"></script>
          <textarea name="content" class="form-control my-editor"></textarea>
          <script>
            var editor_config = {
              path_absolute : "/",
              selector: "textarea.my-editor",
              plugins: [
                "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime media nonbreaking save table contextmenu directionality",
                "emoticons template paste textcolor colorpicker textpattern"
              ],
              toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
              relative_urls: false,
              file_browser_callback : function(field_name, url, type, win) {
                var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
                var y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

                var cmsURL = editor_config.path_absolute + 'laravel-filemanager?field_name=' + field_name;
                if (type == 'image') {
                  cmsURL = cmsURL + "&type=Images";
                } else {
                  cmsURL = cmsURL + "&type=Files";
                }

                tinyMCE.activeEditor.windowManager.open({
                  file : cmsURL,
                  title : 'Filemanager',
                  width : x * 0.8,
                  height : y * 0.8,
                  resizable : "yes",
                  close_previous : "no"
                });
              }
            };

            tinymce.init(editor_config);
          </script>

Any ideas what could be wrong?

As I said - it is fresh Laravel Project with the tinyMCE and UniSharp guided setup.



via Martin Kiss

Unit Testing with mcamara Localization

I'm using mcamara/laravel-localization package and I can't figure out how to make it work with my unit tests. Both of the following fail with red:

// 1. This one results in "Redirecting to http://myapp.dev/en"
$this->get('/')->assertSee('My App Homepage');

// 2. This one results in 404
$this->get('/en')->assertSee('My App Homepage');

In the browser, http://myapp.dev returns 302 with a redirect to http://myapp.dev/en, fair enough. However, http://myapp.dev/en returns 200. So both cases work 100% fine on the front-end, but not with unit tests.

I do have some customization however, which once again, works like charm in the browser.

// in web.php
Route::group([
    'prefix' => app('PREFIX'), // instead of LaravelLocalization::setLocale()
    'middleware' => ['localeSessionRedirect', 'localizationRedirect']],
    function() {
        Route::get('/', function() {
            return view('home');
        });
    }
]);

// in AppServiceProvider.php
public function boot()
{
    // This, unlike LaravelLocalization::setLocale(), will determine the 
    // language based on URL, rather than cookie, session or other
    $prefix = request()->segment(1); // expects 'en' or 'fr'
    $this->app->singleton('PREFIX', function($app) use ($prefix) {
        return in_array($prefix, ['en', 'fr']) ? $prefix : null;
    });
}

Hopefully this code makes sense to you. Thanks!



via Alex

Security issues reported with php, laravel

  1. HTTPOnly not Set on Application Cookie

    session.php line:151 Vulnerable Snippet
    line:151 'secure' => false,

  2. Free proxy issue

    app/config/custom.php Vulnerable Snippet
    free proxy would be leak information in the internet.

  3. X-Frame-Options

    app/config/cors.php line: 31 Vulnerable Snippet
    without set X-Frame-Options in the header. this weakness could be exploit by the clickjacking. ref: https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet

I've been tasked with resolving these issues but am not familiar with the frameworks used. Any direction would be appreciated.

  1. i imagine just setting true is the solution.
  2. there is just a list of ip:port. would i need to eliminate the need for those services
  3. The issue reported is with allowed headers.

    'paths' => [ 'api/' => [ 'allowedOrigins' => [''], 'allowedHeaders' => ['Origin', 'X-Requested-With', 'Authorization', 'Content-Type', 'Accept', 'X-Locale-Id'], 'allowedMethods' => ['POST', 'PUT', 'OPTIONS', 'GET', 'DELETE'], 'maxAge' => 3600, ], This is a service for an iOS app, and has a web admin panel So shouldn't be embedded in any frames. Should i be able to just add the deny option.

If there is a good resource for any of this info that would also be appreciated thank you.



via Sean Carlisle

Laravel: Login screen if not logged in error

First Laravel Project. I want to redirect not logged in users to the login screen.

I configured the auth like in the documentation and found this routes script somewhere:

Route::group(['middleware' => 'auth'], function () {

and pasted it on the beginning of the routes/web.php But now it drops to the myip/login and got routing error.

How to fix it?

(i know that if I delete it it will be fixed, but I want this feature.)



via Feralheart

How to store image path of storage\app\public in laravel-5.4

I am using laravel-5.4 make:auth. In register.blade.php ,added one extra field->profile picture for user .

<form class="form-horizontal" role="form" method="POST" action=""   enctype="multipart/form-data">
                    
                    <div class="form-group">
                        <label for="image" class="col-md-4 control-label"> Profile picture</label>

                        <div class="col-md-6">
                            <input id="image" type="file" class="form-control" name="image">

                            @if ($errors->has('image'))
                                <span class="help-block">
                                    <strong></strong>
                                </span>
                            @endif
                        </div>
                    </div>

I want to store the image path in database.Also I have executed: php artisan storage:link and the [public/storage] directory has been linked.

In app\Http\Controllers\Auth\RegisterController.php:

    public function store(request $request)
{

    if($request->hasFile('image')) {

       $image_name = $request->file('image')->getClientOriginalName();              
        $image_path = $request->file('image')->store('public'); 
        $image = Image::make(Storage::get($image_path))->resize(320,240)->encode();
        Storage::put($image_path,$image);
        $image_path = explode('/',$image_path);

        $user->image = $image_path;
        $user->save();

    } else{

        return "No file selected";

    }       

}

and web.php

Route::post('/store', 'RegisterController@store');
Route::get('/show', 'RegisterController@show');

In database,in user table under image is stored as a temporary path :C:\xampp\tmp\phpC762.tmp. How to store image path of storage\app\public.



via Raja

Sending an array with compact to the view

I have an array like this:

$currentSelection = array('category' => $request->category, 'location' => $request->location);

When I send this to view like this:

return view('index', compact('currentSelection'));

I get this message:

undefined variable currentSelection

How can I send the array properly with compact()?



via Eisenheim

Laravel-datatables protection

I'm using https://github.com/yajra/laravel-datatables currently to send ajax request for my datatable but noticed this:

columns: [
              { data: 'first_name'  },
                { data: 'last_name' },
                { data: 'email' },                  
        ]

but those are lines in my javascript document. I'm currently providing data like this:

return Datatables::of(User::all())->make(true);

That means if someone change lines in my js file he can view columns that he is not supposed to. Now if you take a look at github documentation you can see that this package can also accept collection or query. Is it possible to target only certain columns from database with collection or query ?



via Michael

Laravel does not detect json with axios

I'm sending an ajax request with axios with these headers:

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json'
};

But when I say this in a Laravel 5.4 controller:

if (request()->wantsJson()) {
    $forums = $this->forumInfo->index(Auth::user());
    return response()->json(compact('forums'), 200);
}

return view('home');

The json request is not detected. Also when I look into my headers in chrome dev I can see:

Content-Type:text/html; charset=UTF-8

Why does the header not change approximately to a json content type?



via Jenssen

Eloquqent: LIKE with polymorpic models

Database

I have customers table

id | concrete_id | concrete_type 

customers_person table

id | person_id

customers_entity table

id | entity_id 

person table

id | firstname | lastname

Models

Model Customer defined with

public function person()
{
    return BelongsToMorph::build($this, CustomerPerson::class, 'concrete');
}

BelongsToMorph realization here (Eloquent don't have it default).

And i can get all Customers as Person, it's well work:

Customer::whereHas('person')

My question is: how to get Only those Persons, which contain 'foo' in the lastname?

I try this solution, but it's return only one record (I don't understand why it's happening).

Customer::whereHas('person', function ($query) {
      $query->join('persons', 'persons.id', '=', 'customer_persons.id')
          ->where('persons.lastname', 'like', '%Foo%');
});

This request native SQL look's like this:

    SELECT *
    FROM `customers`
    WHERE EXISTS (
    SELECT *
    FROM `customer_persons`
    INNER JOIN `persons` ON `persons`.`id` = `customer_persons`.`id`
    WHERE `customers`.`concrete_id` = `customer_persons`.`id` 
    AND `customers`.`concrete_type` = 'customer_person' 
    AND `persons`.`lastname` LIKE "%Foo%")



via Stanislav

Laravel complicated relationship approach?

Users(students) all have other users(teachers) assigned to them along with a type for example 1st reviewer or coordinator. Now when a student creates an assessment, the assigned reviewers get the option to accept or decline.

The problem I have is that I cant find a laravel way to make the reviewers aware of the assessments.

Heres a picture of my Schema. http://image.prntscr.com/image/571a8bfdc0cf4964973db336eda287e0.png

Heres part of my user model

public function roles()
{
    return $this->belongsTo(Role::class, 'role');
}

public function reviewers()
{
    return $this->hasMany(Reviewer::class, 'student');
}
public function students()
{
    return $this->hasMany(Reviewer::class, 'teacher');
}
public function assessments()
{
    return $this->hasMany(Assessment::class, 'user_id');
}

Here are the queries and lastly the query I cant figure out.

$student->reviewers => Collection of teachers 
$teacher->students => Collection of students 

$student->assessments => Collection of assessments 
$teacher->assessments => ??? 



via Macdows

Dynamic route path in form action based on the selected option in Laravel 5

I have a form like this in laravel 5.4 view:

<form action="#" method="POST" class="form-inline" role="form">
        
            <div class="form-group">
                <select id="tdcategory" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
                  @foreach($categories as $category)
                        <option value=""></option>
                  @endforeach
                </select>
            </div>
            <div class="form-group">
            <select id="tdlocation" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
                @foreach($locations as $location)
                    <option value=""></option>
                @endforeach
            </select>
            </div>
</form>

I have two questions:

1) How can I dynamically set the form action to something like

categories/{category->id}/locations/{location->id}

Where, both category->id and location->id will be based on the value of the option the user has currently selected

2) Since the form gets submitted as the user changes the option, the page is then reloaded and resets both of the <select> tag. How do I keep track of previously selected option and as the page loads, I can show the user which one did he/she select before the form was submitted?



via Eisenheim

Laravel showing unexpected result, may be caching issue

I have application made in Laravel http://maingolf.co.id/, I am facing issue with single-listing page with shows result of single product. When I visit this link (http://maingolf.co.id/listings/modern-golf-tangerang/1) is shows something else and when I hard refresh this page it shows proper result.

It only displays proper result with hard refresh, maybe it is caching issue or issue in router. This is my live site.



via Chirag Ranpara

Vagrant Windows: Unable to mount one of your Folders

I am trying to install a Homestead on my Win 10 PC and I am currently stuck at this error:

http://prntscr.com/ex2wpd

My Homestead.yaml confing is this:

    folders:
      - map: C:\Projects\Website\Code
       to: /home/vagrant/Code

Any thoughts?



via AlexD

Clear data in modal when click close in Laravel

I have a modal(bootstrap) for create new product. So, when i clicked button close and after that click create new product,the old data still not clear. My code:

<div class="modal fade" id="product" role="dialog" aria-hidden="true" data-target="#myModal"   data-backdrop="static"  data-keyboard="false" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Create new product</h4>
            </div>
            <div class="modal-body">
                <form role="form" action="" method="post" id="frmProduct">
                    
                    <input type="hidden" name="_token" value="">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="">Product Name</label>
                                <input type="text" class="form-control" id="" name="product_name">
                            </div>
                            <div class="form-group">
                                <label for="">Product Type</label>
                                <input type="text" class="form-control" id="" name="product_type_id">
                            </div>
                            <div class="form-group">
                                <label for="">Price</label>
                                <input type="text" class="form-control" id="" name="price">
                            </div>
                            <div class="form-group">
                                <label for="">Status</label>
                                <select class="form-control input-sm m-bot15" id="" name="status">
                                    <option value="0">Inactive</option>
                                    <option value="1">Active</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="img">Image</label>

                                <div class="input-group">
                                    <span class="input-group-btn">
                                        <span class="btn btn-default btn-file">
                                            Choose <input type="file" id="imgInp">
                                        </span>
                                    </span>
                                    <input type="text" class="form-control" name="product_image" readonly>
                                </div>
                                <img id='img-upload' class="image_responsive" />
                            </div>
                        </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="">Description</label>
                            <textarea class="form-control" id="" name="description"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="">Note</label>
                            <textarea class="form-control" id="" name="addition_information"></textarea>
                        </div>

                    </div>
                </div>
            </div>
            <div class="modal-footer">
                    <input type="submit" value="Save" class="btn btn-success">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </form>
    </div>

</div>
</div>

So how can i clear data when clicked close modal?



via John

MySQL cleans column randomly?

I am using a MySQL container from Laradock. When I add valid JSON data to a specific JSON column, after certain time it gets deleted. But when I run docker-compose down and then docker-compose up, MySQL container data in that JSON column magically appears.



via L.Markus

Laravel: multi auth, one login form

In my laravel project i used multi auth system for two separate users but i need one single login page and have to direct it to two user types. Can you suggest any ideas? Checkbox or something like that ?



via Vaclav Kaleta

How to make Laravel belongsTo relation get data according to condition

Using Laravel 5.2, I'm trying to use belongsTo method to get data from more than one table and it should be according to a condition, such as this in Eloquent Model:

public function deals() {
    if($this->section=='offers') {
        return $this->belongsTo('App\Deals\SellOffer', 'record_id');
    } else if($this->section=='requests') {
        return $this->belongsTo('App\Deals\QuoteRequest', 'record_id');
    } else {
        return $this->belongsTo('App\Deals\Partnership', 'record_id');
    }
}

Then inside the controller just call the deals method:

    $data = Options::with('deals')->get();

The Options Table has a column called "section", this should reference to 1 of the 3 tables.

Is that possible to do this, after running the code, it always call the code inside else.



via Marwan

Laravel 5.4 composer error

I am facing a strange issue with Laravel 5.4.9. I tried to install a repository instead might have made a mess by installing it as a controller. Now when I type "php artisan route:list", I am getting this error.

[ReflectionException] Class App\Http\Controllers\ProjectRepositoryInterface does not exist.

This ProjectRepositoryInterface is in repository folder and it works normal.

I want to know where the controller classes are registered and stored? Are they stored in a file (like we bind the repository and interface in the app service provider file).

How to get rid of this error?



via user6404606

Laravel pushing jobs into different queue with low priority

Right now I am using Beanstalkd and Laravel forge for my queues which I fire like this: dispatch(new ProcessPodcast($podcast));

But how do I push a queue into a different job that has a low priority? This will only push the queue into a different job but not set the priority: $job = (new ProcessPodcast($podcast))->onQueue('processing'); dispatch($job);

And if a queue job has a low priority does it mean that it will be fired later when there arent that many queues or how does low priority jobs work?



via user2722667

Laravel and SQS - Several connections in one request

I have a Laravel app (iOS API) that pushes data to SQS to be processed in the background. Depending on the request, we need to dispatch anywhere from 1 to 4 jobs to SQS. For example:

Dispatch a job to SQS, to be processed by a Worker:

  • for connecting to a socket service (Pusher)
  • for connecting to Apple's APNS service (Push Notifications)
  • for sending data to Loggly for basic centralized request logging
  • for storing analytics data in a SQL database (for the time being)

The problem is, we might have a feature like "chat", which is a pretty light request as far as server processing is concerned, however it needs to connect to SQS three times over to send:

  • 1) Socket push to all the devices
  • 2) Analytics processing
  • 3) Centralized Request / Error Logging

In total, these connections end up doubling or tripling the time that the rest of request takes. ie. POSTing to /chat might otherwise take about 40-50ms, but with SQS, it takes more like 100 - 120ms

Should i be approaching this differently? Is there a way batch these to SQS so we only need to connect once rather than 3 times?



via djt

how to make subquery for Eloquent\Relations in laravel

I have three tables

**donates**
id| invoice_id| amount

**donate_project**
id| donate_id| project_id| data_close|

**project**
id| title

I need to get Donates from Project only those which are group by (donate_id , project_id) having (count(*)%2 != 0) like my query below

My code in Project model is valid

public function donates(){
    $id = $this->id; //id of project
    return $query = DB::table('donates')
       ->select('donates.id', 'donates.invoice_id', DB::raw("amount"))
       ->join('donate_project', function($join) use $id {
            $join->on('donate_project.donate_id', '=', 'donates.id')
                 ->where('donate_project.project_id', '=', $id);
        })
    ->groupBy('donate_project.project_id', 'donate_project.donate_id')
    ->havingRaw("count(*) % 2 != 0")
} 

So I try to do like donates() and returns only Collection but I need to return (Illuminate\Database\Eloquent\Relations\Relation)

public function donates()
  {
    return $this->belongsToMany(Donate::class)
        ->getBaseQuery()
        ->selectRaw('sum(donates.amount) as aggregate, donates.id')
        ->groupBy('donate_project.project_id', 'donates.id')
        ->havingRaw('count(*) % 2 != 0');
 }

Is it possible? sorry for my English:)



via Mykhailo Basenko

composer minimum stabilit conflict

"repositories": [  
    {  
        "type": "vcs",  
        "url": "https://github.com/maxim-chugaev/form"  
    },
    {  
        "type": "vcs",  
        "url": "https://github.com/maxim-chugaev/bootforms"  
    }  
],
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.4.*",
    "adamwathan/bootforms": "dev-master@dev",
    "watson/bootstrap-form": "^1.1",
    "laravelcollective/html": "^5.2.0",
    "adamwathan/form": "dev-master@dev"
},

in adamwathan/bootform@master

"repositories": [  
    {  
        "type": "vcs",  
        "url": "https://github.com/maxim-chugaev/form"  
    }  
],
"license": "MIT",
"require": {
    "php": ">=5.4.0",
    "adamwathan/form": "dev-master@dev"
},

but i have

    - adamwathan/bootforms dev-master requires adamwathan/form ^0.8.11 -> satisfiable by adamwathan/form[v0.8.11, v0.8.12] but these conflict with your requirements or minimum-stability.

why? Where does the composer take the version ^0.8.11 of the package adamwathan/form?



via chmax

the correct way to use makeHidden in laravel

I have problem with the pagination .

everything work fine without error but the problem is when i use makeHidden with my code it change the structure of my json pagination result

this is my code

 $result = Job::where('user_id','=',Auth::id())->paginate(5);

    $result= $result->makeHidden(['hasMessage']);

without the second line the result is

 {
    total: 1 ,
    per_page: 5,
    current_page: 1,
    last_page: 1,
    next_page_url: null,
    prev_page_url: null,
    from: 1,
    to: 1,
   data: [
      {
        id: 4,
        sid:125,
        hasMessage: true
    }
        ]
}

but when i use

$result= $result->makeHidden(['hasMessage']);

I got

   [
    {
      id: 4,
      sid:125,
    }
   ]

any idea please ? ? ? is it a bug or there is something wrong ? ?



via programmer

Laravel datatable row details

I am using a single datatable in Laravel 5.4 since it is already implemented in the Laravel framework. My datatable is using query builder to get data, for example using something like this:

@section('content')
<div class="container">
  <table id="services" class="table table-hover table-condensed" style="width:100%">
    <thead>
        <tr>
            <th> </th>
            <th>Id</th>
            <th>Plate</th>
            <th>Brand</th>
            <th>Year</th>

        </tr>
    </thead>
  </table>
</div>

<script type="text/javascript">
$(document).ready(function() {
    table = $('#services').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "",
        "columns": [
            {data: 'id', name: 'id'},
            {data: 'plate', name: 'plate'},
            {data: 'brand', name: 'vehicle.brand'},
            {data: 'year', name: 'vehicle.year'},


        ]
    });    
});  
</script>
@stop

And to get it working proberly, I have to include this file:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Since datatables are included in Laravel, it takes css from bootstrap, javascript from the datatables package installed in laravel.

Now, reading row detail documentation it is a bit unclear, how can I achieve row details in my case. What do I have to add into the code? Do I have to include some more files?

Same with other features as Edit or Remove buttons for each row. Laravel itself doesn't have documentation for datatables so it is a bit confusing what to do now. Thanks for help.



via Ady96

Laravel : Keyword 'create' added to above as well as command

I have build a laravel project where there is keyword called 'create' been added to the above of every page as well as in command prompt. In every page of my application a keyword called 'create' in the above section and in command prompt also. suppose i want to run php artisan migrate, the command start with create and then migration file created same as for every command i run means it starts with create.

But while i run the same command in other projects nothing happened everything run smoothly.

I know the problem is weird but if anyone face the problem before hope help me to find it out.



via User57

how to use different Auth for different controller in laravel?

I am creating a project in laravel. My problem is,Since this is a shopping cart I am using different tables for customer and admins. So if request is admin then i want to authenticate from admin table and if it is from store i want to use customer table for authentication. Is is it possible to set auth table for controllers or is it possible to use create multiple authenticator other than the default?



via Muhammed Hafil

Laravel 5.2 :get checkbox checked

I am trying to get checkbox as checked

Here is my view

<div class="form-group">
                {!! Form::label('extra_services', 'Add extra services') !!}
                <div class="form-group">
                    <?php var_dump (array($temp->extra_services))?>
                    @foreach($extra as $ext)
                        <div class="checkbox">
                            <label>
                                {!! Form::hidden('extra_services', 0) !!}
                                <input type="checkbox" name="extra_services[]" value="{!! $ext->id !!}"
                                       {!! in_array($ext->id, array($temp->extra_services)) ? 'checked' : '' !!} >
                                {!! $ext->title !!}
                            </label>
                        </div>
                    @endforeach
                </div>
            </div>

when I dump my $temp->extra_services I got array(1) { [0]=> string(3) "1,2" }

but in the view the first checkbox only checked the second is not which it should be check too.

what I am doing wrong here.



via Yousef Altaf

Cannot pass blade variable in onChange function in select

I have a select option as below.

 @foreach($destinations as $destination)
{!! Form::select('destination', $counts, $destination->ordering, array('onchange'=>'fetch_select(this.value,$destination->id)') !!}
@endforeach

I am trying to pass a variable called $destination->id in onchange function as above which will trigger a function in java-script later on. However, I am not able to pass this variable like i have done above. Throws a lot of errors. It says

Uncaught SyntaxError: Unexpected token >

in the inspect console.

I tried with:

 'onchange'=>'fetch_select(this.value,destination->id)'
'onchange'=>'fetch_select(this.value,"$destination->id")'
'onchange'=>'fetch_select(this.value,(destination->id))'
'onchange'=>'fetch_select(this.value,($destination->id))'

None of them works .. How can i get around this. With Regards



via mario

With laravel, how can I use event and listener in the package developent

In laravel, I have my own directory structure for package develop and now I need create a event and listener, I registered in the service provider and every thing is set up, I use Event::fire() on the controller and it does not go through the fire(), nothing showing. Has anyone met this problem before?

event and listener:

controller's fire and serviceProvider:



via tao yu

Laravel 5.4 - use a custom attribute model in a collection

  • I have the model Order.
  • Order has many Item.
  • An Item has a price attribute (from the database).
  • An Order has a getAmountAttribute method which looks like this:

/**
 * @return double
 */

public function getAmountAttribute()
{
    return $this->items->sum('price');
}


/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function items()
{
    return $this->hasMany(Item::class);
}

So I can fetch the total price of order's items by simply doing $order->amount.


Now I have a collection of Order and I want to fetch every order that its total price starts at 10. How can I achieve that since I can't use my custom attribute on a where statement?



via Eliya Cohen

Laravel Query builder : left join, select, and where not working

Please help, I'm in trouble, I'm in deadline but the Laravel query builder seems not in a good mood!.

Btw, Here is my table structure :

Table user Structure

ID, USERNAME, NAME, USER_ROLE_MODULE_ID

Table user_role_module Structure

ID, NAME 

And, this is my query builder statement

DB::table('user')
->leftJoin('user_role_module', 'user.id', '=', 'user_role_module.user_id')
->select('user.*', 'user_role_module.name as user_role')
->where("name LIKE '%Jhon%' ") "or other example" ->where("user_role LIKE '%admin%' ")
->paginate(10);

My Goal :

I just want to get all data from user + user role name from user_role_module AND also applies in WHERE statement so I can use it for search feature.

The problem is :

  1. if I search for name, it return error ambiguous column //Laravel is confusing whether taking name from user table or user_role_module table!

  2. if I search for user_role, then the column doesn't exist

Why is it? What is the solution?

Sorry for long question, any answer will highly appreciated!



via Angger

how to create an array for reply keyboard for telegram bot api?

I want to create an array like this for telegram markup:

['بازگشت👆'],
['🛫 از آتن'],

I am using a foreach for this array like this:

$destination = array("بازگشت👆,");
            foreach ($getto->getCity as $key => $todes) 
            {
                $destination[]=array( "'🛬 به "."$todes->city" ." (از " . "$todes->price" ." تومان)'"); 
            }

bot it gave me an array with keys.how can I create an array like that telegram accept?



via mrmrn

laravel mutliple row save to database

I am a laravel beginner. Currently i am learning to do an inventory system. I have two table: goodsreceiveheader and goodsreceivedetail.

What can i do to allow multiple row save into database when submit button are clicked. Hope somebody will help me out as i had stuck in this for a few weeks=(

For goodsreceiveheader table, i have the field of:

id,
referencenumber,
vendorid(FK),
date,
createdby.

While goodsreceivedetail table, i have the field of:

id,
goodsreceiveheader_id(FK),
itemid(FK),
quantity,
costprice.

create.blade.php

@extends('admin.layout')

@section('content')
    <fieldset>
        <legend>Create New Goods Receive</legend>
        @include('layouts.error')
        {!! Form::open(['url' => 'goodsreceive/save', 'method'=>'post']) !!}
        @include('goodsreceiveheader.partial._goodsreceiveheader_form')
        {!! Form::close() !!}


    </fieldset>
@endsection

My view:

<style>
    div#gr{
        padding: 20px;
        border:1px solid black;
    }
</style>
<div class="container">
    <h2>Goods Receive</h2>

    <hr>

        <div id="gr" class="row" style="background-color: lightgoldenrodyellow">

            <div class="col-lg-4 col-sm-6">
                <input name="createdby" type="hidden" value="">
                {!! Form::label('referencenumber', 'Reference Number:')!!}
                <div class="form-group">
                    <input type="text" name="referencenumber" class="form-control" placeholder="Reference Number">
                </div>
            </div>

            <div class="col-lg-4 col-sm-6">
                    {!! Form::label('date', 'Receive Date:')!!}
                    {!! Form::date('date',null,['class'=>'form-control']) !!}
            </div>

            <div class="col-lg-4 col-sm-6">
                {!! Form::label('vendorid', 'Vendor ID:')!!}
                <select name="vendorid" class="form-control">
                    <option value="" selected disabled>Please Select Vendor..</option>
                    @foreach($vendors as $vendor)
                        <option value=""></option>
                    @endforeach
                </select>
            </div>
        </div>
    <br>

    <table class="table table-bordered">
        <thead>
        <th>Item Barcode</th>
        <th>Quantity</th>
        <th>Cost Price</th>
        <th style="text-align: center;background: #eee">
            <a href="#" onclick="addRow()">
                <i class="glyphicon glyphicon-plus"></i>
            </a>
        </th>
        </thead>
        <tbody>
        <tr>
            <td>
                <select class="form-control" name="itemid">
                    <option value="" selected disabled>Select Barcode</option>
                    @foreach($items as $item)
                        <option value=""></option>
                    @endforeach
                </select>
            </td>
            <td><input type="text" name="quantity" class="form-control quantity"></td>
            <td><input type="text" name="costprice" class="form-control costprice"></td>
            <td  style="text-align: center"  onclick="cannotdelete()">
                <a href="#" class="btn btn-danger remove">
                    <i class="fa fa-times"></i>
                </a>
            </td>
        </tr>
        </tbody>
    </table>

    <br>

    <button type="submit" class="btn btn-primary pull-right">Submit</button>

</div>

<script type="text/javascript">
    function addRow()
    {
        var tr='<tr>'+
                '<td>'+
                '<select class="form-control" name="itemid">'+
                '<option value="" selected disabled>Select Barcode</option>'+
                '@foreach($items as $item)'+
                '<option value=""></option>'+
                '@endforeach'+
                '</select>'+
                '</td>'+
                '<td><input type="text" name="quantity" class="form-control quantity"></td>'+
                '<td><input type="text" name="costprice" class="form-control costprice"></td>'+
                '<td class="remove" style="text-align: center"><a href="#" class="btn btn-danger" onclick="deleteRow()"><i class="fa fa-times"></i></a></td>'+
                '</tr>';

        $('tbody').append(tr);
    }

    function deleteRow()
    {
        $(document).on('click', '.remove', function()
        {
            $(this).parent('tr').remove();
        });
    }

    function cannotdelete()
    {
        alert('You cannot delete the first row!!!')
    }

</script>

My controller:

 public function save(GoodsreceiveheaderRequest $request)
    { $data = array(
            'referencenumber'=>$request->referencenumber,
            'vendorid'=>$request->vendorid,
            'date'=>$request->date,
            'createdby'=>$request->createdby,
        );
        $i = DB::table('goodsreceiveheader')->insertGetId($data);

        $goodsreceivedetail = array(
            'goodsreceiveheader_id'=>$i,
            'itemid'=>$request->itemid,
            'quantity'=>$request->quantity,
            'costprice'=>$request->costprice,
        );

        $s = DB::table('goodsreceivedetail')->insert($goodsreceivedetail);

        Session::flash('message','You have successfully create goods receive.');

        return redirect('goodsreceive/goodsreceiveheader_list');
    }



via Nick

Saturday, April 15, 2017

LARAVEL - Not able to call a function inside a controller method

Here is comment method of CommentController

 public function comment(Request $request)
        {

    $comments = DB::table('comments')
                            ->join('answers', 'answers.id' , '=', 'comments.answer_id')
                            ->join('users' , 'users.id' , '=', 'comments.user_id')
                            ->where('answers.id', '=' , '9')
                            ->where('parent_id', '0')
                            ->select('comments.comment as comment',
                                    'comments.id as comment_id',
                                    'comments.created_at as created_at',
                                    'comments.parent_id as parent_id',
                                    // 'answers.aanswer as answer',
                                    'answers.id as ans_id')

                            ->orderBy('created_at', 'desc')
                            ->get();


 foreach ($comments as $comment) {
            echo $comment->comment_id.$comment->comment.'<br>';
            return $this->testingComment();
           }


public function testingComment(){
                    echo "testing comments function";
                   }

    }

I have this foreach loop , I am just t trying to call this testingComment function in loop, but its not working.

I am building a nested comment system and i want to call function inside foreach loop to render child and sub child comments when a when a parent_id matches



via waq

Laravel 5.4 route group and resource mess up the parameters

This resource definition is good:

Route::resource('servers', 'ServerController');

Gives:

+--------+-----------+-----------------------+-----------------+-----------------------------------------------+--------------+
| Domain | Method    | URI                   | Name            | Action                                        | Middleware   |
+--------+-----------+-----------------------+-----------------+-----------------------------------------------+--------------+
|        | GET|HEAD  | servers               | servers.index   | App\Http\Controllers\ServerController@index   | web          |
|        | POST      | servers               | servers.store   | App\Http\Controllers\ServerController@store   | web          |
|        | GET|HEAD  | servers/create        | servers.create  | App\Http\Controllers\ServerController@create  | web          |
|        | GET|HEAD  | servers/{server}      | servers.show    | App\Http\Controllers\ServerController@show    | web          |
|        | PUT|PATCH | servers/{server}      | servers.update  | App\Http\Controllers\ServerController@update  | web          |
|        | DELETE    | servers/{server}      | servers.destroy | App\Http\Controllers\ServerController@destroy | web          |
|        | GET|HEAD  | servers/{server}/edit | servers.edit    | App\Http\Controllers\ServerController@edit    | web          |
+--------+-----------+-----------------------+-----------------+-----------------------------------------------+--------------+

But I need to wrap it into a group with prefix like this:

Route::group(['prefix' => 'servers'], function()
{
    Route::resource('/', 'ServerController', ['names' => 'servers']);
});

And here comes the problem, because of prefix the parameterised routes' parameters are empty:

+--------+-----------+-----------------+-----------------+-----------------------------------------------+--------------+
| Domain | Method    | URI             | Name            | Action                                        | Middleware   |
+--------+-----------+-----------------+-----------------+-----------------------------------------------+--------------+
|        | GET|HEAD  | servers         | servers.index   | App\Http\Controllers\ServerController@index   | web          |
|        | POST      | servers         | servers.store   | App\Http\Controllers\ServerController@store   | web          |
|        | GET|HEAD  | servers/create  | servers.create  | App\Http\Controllers\ServerController@create  | web          |
|        | GET|HEAD  | servers/{}      | servers.show    | App\Http\Controllers\ServerController@show    | web          |
|        | PUT|PATCH | servers/{}      | servers.update  | App\Http\Controllers\ServerController@update  | web          |
|        | DELETE    | servers/{}      | servers.destroy | App\Http\Controllers\ServerController@destroy | web          |
|        | GET|HEAD  | servers/{}/edit | servers.edit    | App\Http\Controllers\ServerController@edit    | web          |
+--------+-----------+-----------------+-----------------+-----------------------------------------------+--------------+

So the servers/1 goes 404. Is there any way to fix this problem?



via MrRP

Accessing session variable inside css file laravel

I have a css file name style-usercolors.css.php for dynamic css color in my laravel app. Inside the file I can declare variable and use it, but can't access the session variable.

header("Content-type: text/css");

$primaryColor = session()->has('ORGANISATION_SETTINGS') ? session()->get('ORGANISATION_SETTINGS')['style_settings']['primary_color'] : '#F18805';
$secondaryColor = session()->has('ORGANISATION_SETTINGS') ? session()->get('ORGANISATION_SETTINGS')['style_settings']['secondary_color'] : '#20576B';
$offwhite = '#f6f6f6';



via hizbul25

Laravel Secondary database connection does not work

I have one mysql database connection in config/database.php as below and it is working fine.

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

I am trying to define another alternate connection (for testing purposes) as below. (Same host but different database):

'mysql_testing' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE_TEST', 'forge'),
    'username' => env('DB_USERNAME_TEST', 'forge'),
    'password' => env('DB_PASSWORD_TEST', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

where DB_DATABASE_TEST, DB_USERNAME_TEST and DB_PASSWORD_TEST are defined in .env as below:

DB_DATABASE_TEST=db_other
DB_USERNAME_TEST=usr_other
DB_PASSWORD_TEST=secret

However, this second connection does not work.

In tinker, if I try to use the new connection:

DB::connection('mysql_testing')->getPdo()
InvalidArgumentException with message 'Database [mysql_testing] not configured.'

And if I try to check the config values, mysql works but the new connection mysql_testing returns null:

Config::get('database.connections.mysql')
[
 "driver" => "mysql",
 "host" => "127.0.0.1",
 "port" => "3306",
 "database" => "***",
 "username" => "***",
 "password" => "***",
 "charset" => "utf8",
 "collation" => "utf8_unicode_ci",
 "prefix" => "",
 "strict" => false,
 "engine" => null,
]

Config::get('database.connections.mysql_testing')
null

Any idea how may I debug this issue?



via hashbrown

Laravel : QUERY BUILDER SELECT ON WHERE LIKE STATEMENT

I have a Query Builder problem on Laravel 5.4,

I want to select only certain field on where statement.

if I don't put WHERE statement function the SELECT function performed nicely, but when I put WHERE LIKE function then seems the SELECT function not working and it automatically selecting all (*)

Fyi, both user and address table has 'name' field. it only select name from user table. it work nicely.

DB::table('user')
-leftJoin('address', 'user.id', '=', 'address.user_id')
->select('user.name')
->get();

but this is not working

DB::table('user')
-leftJoin('address', 'user.id', '=', 'address.user_id')
->select('user.name')
->where('user.name', 'LIKE', '%jhon%')
->get();

how do I accomplish this? Any anwer will be highly appreciated!



via Angger

How to use traits in Laravel 5.4.18?

I need an example of where to exactly create the file, to write to it, and how to use the functions declared in the trait. I use Laravel Framework 5.4.18

-I have not altered any folder in the framework, everything is where it corresponds-

From already thank you very much.



via emi

Laravel 5.4 password reset using ajax

I have this code:

 $.ajax({
               url:"/password/email", 
               data: {
                     _token: $(".modal-forgotpass-content input[name='_token']").val(),
                     email: $(".modal-forgotpass-content input[name='email']").val()
                },
                type: "POST",
                success: function(data) {
                    alert("Successful : link send");
                },
                error: function(e) {
                     alert("Faild: link not send");
                }

Controller (this function is coming with laravel 5.4) :

 public function sendResetLinkEmail(Request $request)
    {
        $this->validate($request, ['email' => 'required|email']);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $request->only('email')
        );

        return $response == Password::RESET_LINK_SENT
                    ? $this->sendResetLinkResponse($response)
                    : $this->sendResetLinkFailedResponse($request, $response);
    }

Routes :

Auth::routes();

this code its work well ,but he send password reset link to all emails even if the email not exist in database(users table) i want the link to be sent only to the emails already exist in user table any help? Thank you



via Ilham Guezzoula

Retrieve the author of the last comments

I want to retrieve the name of the person who posted the last comment in a topic for a forum. This is what I do at PhpMyAdmin and that works so I get the right values:

select commentaires.auteur 
from commentaires inner join sujets on commentaires.sujet_id = sujets.id
where commentaires.id = (
    select max(commentaires.id)
    from commentaires inner join sujets on commentaires.sujet_id = sujets.id
    where sujets.id = 12
);

I thought using QueryBuilder to retrieve the values I wanted but I realize it's quite complex .. Here is one of my essays:

DB::table('commentaires')->join('sujets', 
'sujets.id','=','commentaires.sujet_id')  
->where(['commentaires.id' => DB::raw('max(commentaires.id')])
->where('sujets.id','=', $unSujet->id)
->value('commentaires.auteur')

Or would you have a simpler idea? Thank you in advance for your help.



via B.Rousseaux

Advertisement