Wednesday, February 28, 2018

how to use if statements in php to echo out just one variable - development

how to use if statements in php to echo out just one variable

I have this code below which outputs several values in kilometers after a computation. how can I limit it to bring out a single output given the condition that if $miles is less than 20km,it should echo “you will get a mechanic in an hours time”. here is the code:

    $theta = $driver_long - $longitude->lng;
    $dist = sin(deg2rad($driver_lat)) * sin(deg2rad($data3->lat)) +  cos(deg2rad($driver_lat)) * cos(deg2rad($data3->lat)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515 * 1.609344 ."km";
  echo "
    <div class='form-group'>
           <input type='text' value='".$miles."' disabled>
           <input type='hidden' value='".$miles."' name='distance[]'>

        </div>
    ";
    if ($miles < 20){
        echo "a mechanic would get to you in about an hour's   time";

    }elseif ($miles <40) {
        echo "a mechanic would get to you in about an 2 hour's  time";
    } 
    else {
        echo "no mechanic withing that location found";
    }
    ?>



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-use-if-statements-in-php-to-echo-out-just-one-variable/
via Lzo Media

Realtime validation using Laravel - development

Realtime validation using Laravel

I am using Laravel Framework and i’m new in this Framework. This scenario is my problem.

Scenario: User A review some of document once they click the “Edit” button (unlocked document), other user can’t review
that document because the system will be locked other user to review in the same time. I’ve got this.

But, the problem is, how can the system set once User A click “Edit” button, the time automatically running within in 4 hours.
When the time is finish, automatically review document of User A will be locked and “Edit” button will show to the other user.

This is example of the interface.
enter image description here

Here is my index.blade code

<td>
            <a title="View Detail" data-pjax="pjax-modal-container" type="button" class="btn btn-xs btn-info" href=""><i class="fa fa-eye"></i></a>
            @if($modelItemReviewReviewer->status_id==303)
            <a title="No Review" type="button" class="btn btn-xs btn-danger"><i class="fa fa-lock"></i></a>
            @elseif ($modelItemReview->lock_item==1 && $modelItemReviewReviewer->status_id==301)
            <a title="No Review" type="button" class="btn btn-xs btn-danger"><i class="fa fa-lock"></i></a>
            @elseif ($modelItemReview->lock_item==1 && $modelItemReviewReviewer->status_id==302)
            <a title="Can Review" type="button" class="btn btn-xs btn-primary"><i class="fa fa-unlock"></i></a>
            @else
            <a title="Can Review" type="button" class="btn btn-xs btn-primary"><i class="fa fa-unlock"></i></a>
            @endif
            @if($modelItemReviewReviewer->status_id==302 && ($modelItemReviewReviewer->upload_id != null || $modelItemReviewReviewer->remark != null))
            <a title="Submit Confirmation" data-pjax="pjax-modal-container" data-id="" type="button" class="btn btn-xs btn-success update_status"><i class="fa fa-check-circle"></i></a>
            @include('item_review_reviewer.modal_update_status')
            @endif
        </td>

And here is my controller:

public function show(Request $request, $id) {
    $modelItemReviewReviewer = ItemReviewReviewer::findOrFail($id);

    if ($modelItemReviewReviewer->status_id == 301 && $modelItemReview->lock_item == 2) {
        $modelItemReviewReviewer->status_id = 302; //Item on Review
        AppClassesAuditTrailHelper::logAuditUpdate("item_review_reviewers", $modelItemReviewReviewer->id, $modelItemReviewReviewer);
        $modelItemReviewReviewer->updated_by = Auth::user()->id;
        $modelItemReviewReviewer->save();

        $modelItemReview->lock_item = 1;
        AppClassesAuditTrailHelper::logAuditUpdate("item_reviews", $modelItemReview->id, $modelItemReview);
        $modelItemReview->updated_by = Auth::user()->id;
        $modelItemReview->save();
    }

    return view('index.blade', compact('modelItemReviewReviewer','modelItemReview','request'));
}

Can someone show me how it’s work ?



from Laravel Questions and Answers https://laravelquestions.com/laravel/realtime-validation-using-laravel/
via Lzo Media

whereNotBetween not working as expected - development

whereNotBetween not working as expected

I am trying to exclude a given range of ids when I select the records and I am trying to use whereNotBetween()

But it returns all the records instead of the records which does not have id in the given range. and yes the id is a mongodb string type.

    return Contact::whereNotBetween('id', ["1","2"])->get();

I don’t think it’s an issue with string keys as whereBetween() works just fine with string keys.

The Schema is something like this:

{
    "_id": "5a9633de072e10085205c912",
    "id": "1",
    "name": "sapnesh",
    "nick_name": "sap",
    "address": {
        "permanent": {
            "city": "Karwar",
            "state": "Karnataka",
            "PinCode": "581324"
        },
        "temperory": {
            "city": "Bangalore",
            "state": "Karnataka",
            "PinCode": "560040"
        }
    },
    "updated_at": "2018-02-28 04:45:18",
    "created_at": "2018-02-28 04:45:18"
}

What is the issue here?



from Laravel Questions and Answers https://laravelquestions.com/laravel/wherenotbetween-not-working-as-expected/
via Lzo Media

Laravel Model – Want to check where (or) orWhere in DB::raw - development

Laravel Model – Want to check where (or) orWhere in DB::raw

This is my model function now its working correctly, but i want to check where (or) orwhere. I Already try that but cant get the apt answer

public static function getPlacementCountByStatus(){
        $countStatus = DB::table('placements')->where('status','1')->select(DB::raw('count(joborderid) as total, joborderid'))->groupBy('joborderid')->get();
    return $countStatus;
    }

I want to check something like this

->where('statusid','=','3')->orWhere('statusid','=','4')->orWhere('stageid','=','4')->orWhere('stageid','=','8');

// i want to check this in my $countStatus something like and or condition in my db::raw query



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-model-want-to-check-where-or-orwhere-in-dbraw/
via Lzo Media

Multiple records are created for same order - development

Multiple records are created for same order

I am using Database Transaction for a endpoint where staff can accept the order perform certain operation thereafter. I don’t want same order to be assigned to different staff.I used Database transaction for that but the problem is multiple staff are assigned to same order when the staff accepts the order at same time.
The sample code is provided below:

try {
        $message = [
            "status_validation" => "Input status must have value assigned",
            "unique" => "Order is assigned to other driver"
        ];
        $this->validate($request, [
            "restaurant_id" => 'required|integer|min:1',
            "order_id" => 'required|integer|min:1|unique:driver_order,order_id',
            "status" => 'required|status_validation'
        ], $message);
    } catch (Exception $ex) {
        return response()->json([
            "status" => "422",
            "message" => $ex->response->original
        ], 422);
    }
    try {

        DB::beginTransaction();
        $assignOrderToDriver = $this->driverOrder->createDriverOrder($request);
        DB:commit();

        return response()->json([
            "status" => "200",
            "message" => "Order has been sucessfully assigned."
        ], 200);
    }
    catch (Exception $ex) {
        return response()->json([
            "status" => "500",
            "message" => $ex->getMessage()
        ], 500);
    }

This issue is really creating problem in my project.Am i doing something wrong here ? Thank you.



from Laravel Questions and Answers https://laravelquestions.com/php/multiple-records-are-created-for-same-order/
via Lzo Media

How to rewrite htaccess file for remove public path? - development

How to rewrite htaccess file for remove public path?

I now write project in Laravel 5.6 and I must remove public path from URL. I have .htaccess file in root directory Laravel with code:

<IfModule mod_rewrite.c>
   RewriteEngine On 
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

But in my view files URL’s to assets not working correctly. For example this path not work correctly

<link href="" rel="stylesheet">
<link href="css/app.css" rel="stylesheet">

But if I add public path to assets path all working:

<link href="public/css/app.css" rel="stylesheet">

How can be work path to asstes without adding public path to assets URL?



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-rewrite-htaccess-file-for-remove-public-path/
via Lzo Media

Laravel swap the position in collection – multidimensional array - development

Laravel swap the position in collection – multidimensional array

Following is the array in the collection:

array:1 [▼
  "online" => array:2 [▼
    "IS-003" => array:19 [▼
      "product" => Product {#831 ▶}
      "quantity" => 1
      "payment-option" => "online"
    ]
    "HA4" => array:19 [▼
      "product" => Product {#822 ▶}
      "quantity" => 1
      "payment-option" => "online"
    ]
  ]
]

Whenever a user changes the payment-option, accordingly the above array should change.

For instance, if HA4['payment-option'] is changed from online to cod, then there should be 2 arrays in parent array.
Following is the array that I want as result.

array:2 [▼
  "online" => array:1 [▼
    "IS-003" => array:19 [▼
      "product" => Product {#831 ▶}
      "quantity" => 1
      "payment-option" => "online"
    ]
  ]
  "cod" => array:1 [▼
    "HA4" => array:19 [▼
      "product" => Product {#822 ▶}
      "quantity" => 1
      "payment-option" => "cod"
    ]
  ]
]

The thing that I have tried so far but couldn’t get the desired result:

$paymentOptionCart = collect();

foreach ($cart as $paymentType => &$details) {
    foreach ($details as $c => $p) {
        if ($c == $code) {
            $details[$c]['payment-option'] = $request->option;
            $paymentOptionCart->put($paymentType, $details);

            unset($details[$c]);
        }
    }
}

On executing the above code, nothing happens except the payment-option is updated to cod.

I know I am making a silly mistake somewhere, but I am unable to locate where and how.

Can anybody help me out?



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-swap-the-position-in-collection-multidimensional-array/
via Lzo Media

Laravel Users follow - development

Laravel Users follow

I have this error

SQLSTATE[23000]: Integrity constraint violation: 1052 Column ‘id’ in field list is ambiguous (SQL: select id, followers.user_id as pivot_user_id, followers.follows_id as pivot_follows_id, followers.created_at as pivot_created_at, followers.updated_at as pivot_updated_at from users inner join followers on users.id = followers.follows_id where followers.user_id = 1 and follows_id = 2 limit 1)

(View: /Users/harshitsingh/Documents/logos/resources/views/users/index.blade.php)
and this is my UsersController

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppUser;
use Image;
use Auth;
use Profile;
use AppPost;
use AppNotificationsUserFollowed;

class UsersController extends Controller
{
    public function index()
    {
        $users = User::where('id', '!=', auth()->user()->id)->get();
        return view('users.index', compact('users'));
    }

    public function profile(){
        return view('profile');
    }


    public function update_avatar(Request $request){

            // Handle the user upload of avatar
        if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            Image::make($avatar)
            ->resize(300, 300)
            ->save( public_path('/uploads/avatars/' . $filename ) 
        );

            $user = Auth::user();
            $user->avatar = $filename;
            $user->save();
        }

        return redirect('/');

    }

    public function follow(User $user)
    {
        $follower = auth()->user();
        if ($follower->id == $user->id) {
            return back()->withError("You can't follow yourself");
        }
        if(!$follower->isFollowing($user->id)) {
            $follower->follow($user->id);

            // sending a notification
            $user->notify(new UserFollowed($follower));

            return back()->withSuccess("You are now friends with {$user->name}");
        }
        return back()->withError("You are already following {$user->name}");
    }

    public function unfollow(User $user)
    {
        $follower = auth()->user();
        if($follower->isFollowing($user->id)) {
            $follower->unfollow($user->id);
            return back()->withSuccess("You are no longer friends with {$user->name}");
        }
        return back()->withError("You are not following {$user->name}");
    }

    public function notifications()
    {
        return auth()->user()->unreadNotifications()->limit(5)->get()->toArray();
    }


    public function show(Post $post, $id)
    {
        $user = User::findOrFail($id);
        return view('user.profile', compact('user'));
    }
}

I am trying user to user relationship
this is User Model
`

 public function followers() 
        {
            return $this->belongsToMany(self::class, 'followers', 'follows_id', 'user_id')
                        ->withTimestamps();
        }

        public function follows() 
        {
            return $this->belongsToMany(self::class, 'followers', 'user_id', 'follows_id')
                        ->withTimestamps();
        }

        public function follow($userId) 
        {
            $this->follows()->attach($userId);
            return $this;
        }

        public function unfollow($userId)
        {
            $this->follows()->detach($userId);
            return $this;
        }

        public function isFollowing($userId) 
        {
            return (boolean) $this->follows()->where('follows_id', $userId)->first(['id']);
        }

`



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-users-follow/
via Lzo Media

why laravel use @ symbol to aid views by generating various function - development

why laravel use @ symbol to aid views by generating various function

actually I m totaly new in laravel. actually one of the view file i have used some content like @yield(‘content’). i have understand that this yield is a function for laravel. but my problem is why this @ sign has been used before such type of function.



from Laravel Questions and Answers https://laravelquestions.com/laravel/why-laravel-use-symbol-to-aid-views-by-generating-various-function/
via Lzo Media

Laravel mix generating blank page - development

Laravel mix generating blank page

I’m using laravel mix to pre-compile my code. When I run npm run dev or npm run production, I only get a white screen. So i did git checkout --f public/js/app.js and then everything work, but when y execute npm run production, the white screen appears again.

I also did a video to show what is going on: https://www.youtube.com/watch?v=WkPEdxj4HT4

Also here is my webpack.mix.js

let mix = require('laravel-mix');
mix.webpackConfig({
  node: {
    fs: 'empty'
  }
});

// Manage the environments
require('dotenv').config();

// // Enables Browser sync
//  Doc: https://github.com/JeffreyWay/laravel-
mix/blob/master/docs/browsersync.md
//  Browsersync: https://browsersync.io/
// Browsersync enables livereloads and live pushes
let proxyUrl = process.env.BROWSERSYNC_PROXY_URL || 'localhost';
mix.browserSync(proxyUrl);

mix.js('resources/assets/js/app.js', 'public/js')
.version();

mix.sass('resources/assets/sass/app.scss', 'public/css')
.version();



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-mix-generating-blank-page/
via Lzo Media

Sunday, February 25, 2018

Laravel unique validation - development

Laravel unique validation

How can I perform this migration rule to laravel validation rule

$table->unique(['field_1', 'field_2']);

so far I tried this but I still got no result?

$rules = [
            'slug' => 'required|max:70|unique:categories,slug,null,id,category_type,' . Blog::class . '|regex:/(^[A-Za-z-_ ]+$)+/',
            'title' => 'required|max:70',
        ];



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-unique-validation/
via Lzo Media

Ajax Error Message cannot Display in bootstrap modal in Laravel Blade - development

Ajax Error Message cannot Display in bootstrap modal in Laravel Blade

I am trying to insert ‘section’ value into ‘class_sections’ table using ajax with bootstrap modal. Data is inserting successfully and I am getting return response if success or error.Now, the problem is errors or success message is not showing in the modal. Where in I am doing false, would someone help me, please?
My index.blade.php is-

<button type="button" class="btn btn-info" data-toggle="modal" data-target="#sectionModal" data-whatever="@fat">+New Section</button>
   <div class="modal fade" id="sectionModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel1">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
           <div class="modal-header">
             <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
             <h4 class="modal-title" id="exampleModalLabel1">New Section</h4>
           </div>
           <form id="AddNewSection" method="POST">
              
           <div class="modal-body">
              <div id="success-msg" class="hide">
                 <div class="alert alert-info alert-dismissible fade in" role="alert">
                  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                  </button>
                 <strong>Success!</strong> You Created New Section!!
                 </div>
              </div>
              <div class="form-group">
                 <input type="text" name="section" value="" class="form-control" placeholder="Section Name">
                  <span class="text-danger">
                     <small id="section-error"></small>
                  </span>
              </div>
          </div>
          <div class="modal-footer">
             <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
             <button type="submit" class="btn btn-primary">Save section</button>
          </div>
        </form>
      </div></div></div>

Ajax:

<script type="text/javascript">
$('body').on('click', '#AddNewSection', function(){
    var sectionForm = $("#AddNewSection");
    var formData = sectionForm.serialize();
    $( '#section-error' ).html( "" );

    $.ajax({
        url:'admin/class-section/store',
        type:'POST',
        data:formData,
        success:function(data) {
           // console.log(data);
            if(data.errors) {
                if(data.errors.section){
                    $( '#section-error' ).html( data.errors.section[0] );
                }

            }
            if(data.success) {
                $('#success-msg').removeClass('hide');
                setInterval(function(){ 
                    $('#sectionModal').modal('hide');
                    $('#success-msg').addClass('hide');
                }, 3000);
            }
        },
    });
});</script>

ClassSectionController.php

public function store(Request $request)
{
  $validator = Validator::make($request->all(), [
                'section' => 'required|max:255|unique:class_sections',
            ]);

  $input = $request->all();

  if ($validator->passes()) {

       // Store section in database
       $data = new ClassSection;
       $data->section = $request->section;
       $data->save();

       return response()->json($data);

      }

  return Response::json(['errors' => $validator->errors()]);
}



from Laravel Questions and Answers https://laravelquestions.com/laravel/ajax-error-message-cannot-display-in-bootstrap-modal-in-laravel-blade/
via Lzo Media

Auth0 and Laravel Spark - development

Auth0 and Laravel Spark

There are many great tutorials on how to integrate Auth0 with Laravel but I can’t find any guides on how to integrate with Laravel Spark.

If anyone has some experience with getting it up and running with the Spark User Repository I would be eternally grateful if you could share your knowledge.

submitted by /u/scottybowl
[link] [comments]



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/auth0-and-laravel-spark/
via Lzo Media

Laravel models acts like array? - development

Laravel models acts like array?

I know about PHP Array Objects but I have never seen laravel models working like this…Its kinda strange. Heres the actual code..

 public function getUserChats()
{
    $users = [];
    $chats1 = Chat::where('sender_id','=',auth()->user()->id)->get();
    $chats2 = Chat::where('reciever_id','=',auth()->user()->id)->get();
    foreach ($chats2->toArray() as $chat2) {
        $user = new UserResource(User::where('id','=',$chat2['sender_id'])->first());
        array_push($users, $user);
    }
    foreach ($chats1->toArray() as $chat1) {
        $user = new UserResource(User::where('id','=',$chat1['reciever_id'])->first());
        array_push($users, $user);
    }
    return $users;
}


//The above method works but this one doesn't works
 public function getUserChats()
{
    $users = [];
    $chats1 = Chat::where('sender_id','=',auth()->user()->id)->get();
    $chats2 = Chat::where('reciever_id','=',auth()->user()->id)->get();
    foreach ($chats2->toArray() as $chat2) {
        $user = new UserResource(User::where('id','=',$chat2->sender_id)->first());
        array_push($users, $user);
    }
    foreach ($chats1->toArray() as $chat1) {
        $user = new UserResource(User::where('id','=',$chat1->reciever_id)->first());
        array_push($users, $user);
    }
    return $users;
}

Notice inside the for each loop how I have to access the sender_id from $chat1 and $chat2 . I want to know whats actually going on .. Its more of a theoretical
question…Thanks for the response



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-models-acts-like-array/
via Lzo Media

Laravel5.5: Insert the ID of the created model to create a record in another table - development

Laravel5.5: Insert the ID of the created model to create a record in another table

I have been trying to create a record of a table B using the id of a created record in table A. But for some reason, the field is always null even though i have dumped the value of the model id and it’s correct. but when i assign it to a field in table B it doesn’t insert it. I don’t get any errors, and both records are created(in Table A and B) but the value of the field that is supposed to have the ID of model A is NULL.

I have added the field to the $fillable array in the model class:

protected $fillable = [
        'name', 'email', 'password', 'phone', 'role', 'A_id', 
    ];

Here is the code I tried. Please help me solve this issue.

if($data['role'] == 'admin'){

            $tableA = TableA::create([
                'name' => $data['name'],
                'phone' =>$data['phone']
            ]);
            return TableB::create([
                'A_id' => $tableA->id,
                'name' => $data['nameB'],
                'email' => $data['email'],
                'role' => $data['role'],
                'phone' => $data['phoneB'],
                'password' => bcrypt($data['password']),
            ]);
        }

Here is the migration file for TableB

public function up()
    {
        Schema::create('tableB', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('A_id')->unsigned()->nullable();
            $table->string('phone', 10)->unique();
            $table->string('name');
            $table->string('role');
            $table->integer('address_id')->nullable();
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel5-5-insert-the-id-of-the-created-model-to-create-a-record-in-another-table/
via Lzo Media

Laravel Chat with Pivot Table how to return same users to same chat - development

Laravel Chat with Pivot Table how to return same users to same chat

I am Developing a chat system , I have three tables (users , chats , user_chat) where is the user chat is the pivot table ,
I want to check every time that same users want to communicate to back to there chat room and don’t create a new chat room

like

enter image description here

thats means that whenever **user_id:15**
and **user_id:20** wish to communicate return them to **chat_room:1** and not create a new one how to do it
I already tried array_intersect() but i didn’t get any result

public function store(Request $requests){
//$requests->user()->id;
$data = $requests->all();
$username1 = User::select('username')->where('id',auth()->guard('api')->user()->id )->first();
$username2 = User::select('username')->where('id',$data['recever_id'] )->first();
$user1Conve[] = Conversation::where('user_id' , '=',auth()->guard('api')->user()->id )->select('chat_room_id')->get();
$user2Conve[] = Conversation::where('user_id' , '=',$data['recever_id'] )->select('chat_room_id')->get();
$result = array_intersect($user2Conve, $user1Conve);
if (count($result) == 0) {

    $chatroom = ChatRoom::create([
        'room_name' => 'محادثة بين' . $username1->username . ' و ' . $username2->username . '', 'sender_id' => auth()->guard('api')->user()->id

    ]);
    $lastId = (int)$chatroom->id;

    Conversation::create(['chat_room_id' => $lastId, 'user_id' => auth()->guard('api')->user()->id]);
    Conversation::create(['chat_room_id' => $lastId, 'user_id' => $data['recever_id']]);

    $message = Messages::create(
        ['message' => $data['message'],
            'user_room_id' => $lastId,
            'user_id' => auth()->guard('api')->user()->id,
        ]);
    $success['chat_room_id'] = $chatroom->id;
    $success['arrayIntersct'] = $result;
    $pusher = new Pusher("418914066f12eac2d5fd", "6e1b5e98b06d7d3ebd7a", "449820", array('cluster' => 'ap2'));
    $pusher->trigger('my-channel', 'my-event', array('message' => $message->message));
}
else {

}

  return response()->json(['code'=>'success','success'=>$success], $this->successStatus);

}



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-chat-with-pivot-table-how-to-return-same-users-to-same-chat/
via Lzo Media

SSL Certificate on Laravel Development - development

SSL Certificate on Laravel Development

I have an application which i am using ‘php artisan serve’ command to run it on my mobile. I want to test it on my mobile but i have an API which requires HTTPS. So how can i configure this? I want to test this before I put this live.

Here is how my artisan command looks like:

php artisan serve --host=192.168.1.18 --port=80

The IP is my local machines IP Address which i am accessing from my mobile.

I have tried looking up google but i couldn’t find the answer i was looking for.

Thanks



from Laravel Questions and Answers https://laravelquestions.com/laravel/ssl-certificate-on-laravel-development/
via Lzo Media

How can I pass file uploaded and pass parameter with axios on vue component? - development

How can I pass file uploaded and pass parameter with axios on vue component?

My vue component to upload file image like this :

<template>
    <section>
        <ul class="media-list">
            ...
        </ul>
    </section>
</template>

<script>
    export default {
        ...
        props: ['productId'],
        methods: {
            ...
            onFileChange(e, index) {
                let files = e.target.files,
                let formData = new FormData()
                formData.append('file', files[0])
                axios.post(window.App.baseUrl+'/admin/product/upload-image',
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                ).then(function(){
                    console.log('SUCCESS!!')
                })
                .catch(function(){
                    console.log('FAILURE!!')
                });
            }
        }
    }
</script>

So it will call onFileChange method if user upload file image

My routes like this :

Route::prefix('admin')->group(function(){
    Route::prefix('product')->group(function(){
        Route::post('upload-image', 'AdminProductController@uploadImage')->name('admin.product.upload-image');
    });
});

My controller like this :

public function uploadImage(Request $request)
{
    echo '<pre>';print_r($request->all());echo '</pre>';die();
}

The code works. I success get file uploaded in the controller

But here I want to pass another paramater too. I want to pass parameter productId

I try change code axios like this :

...
axios.post(window.App.baseUrl+'/admin/product/upload-image',
{product_id: this.productId, formData}
...

It does not work. The result is empty

How can I solve this problem?



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-can-i-pass-file-uploaded-and-pass-parameter-with-axios-on-vue-component/
via Lzo Media

QueryException Laravel : Driver not found - development

QueryException Laravel : Driver not found

I am facing a strange error with laravel under ubuntu using PostgreSql.
Its NOT a PDOException. The database migration is successful so all driver are set and PDO connection is also eshtablished. But why this error?

Didn’t find much about it in google. I am attaching the screenshot.

This is NOT homestead rather own lamp stack.
enter image description here

Regards



from Laravel Questions and Answers https://laravelquestions.com/php/queryexception-laravel-driver-not-found/
via Lzo Media

Laravel one to many relation delete request with guzzle - development

Laravel one to many relation delete request with guzzle

I have two table, Book and Author, use one to many relation, Author as parent and Author as child. I used Guzzle for client request to Book and Author. But the problems when delete book table request from client app, getting error like this

    GuzzleHttp  Exception  ServerException (500)
Server error: `DELETE http://localhost:8080/api/author/4` resulted in a `500 Internal Server Error` response: <!DOCTYPE html> <html> <head> <meta name="robots" content="noindex,nofollow" /> <style> (truncated...)

and sometimes its success but parent table (Author) removed too.
And when i make request with postman all is work fine.

Its my code, thanks before.

Book controller API

<

?php

namespace AppHttpControllers;

use AppBook;
use IlluminateHttpRequest;
use DB;

/**
* 
*/
class BookController extends Controller

{
    public function allBook()
    {
        return response()->json(Book::all());
    }

    public function Book($id)
    {
        return response()->json(Book::find($id));
    }

    public function createBook(Request $request)
    {
        $book = Book::all();
        return Book::create($request->all());
    }

    public function updateBook($id, Request $request)
    {
        $book = Book::find($id);
        $book->update($request->all());

        return response()->json($book, 200);
    }

    public function deleteBook($id)
    {
        Book::find($id)->delete();
        return response('Book deleted', 200);
    }
}

Book migration table

 <?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('genres');
            $table->text('synopsis');
            $table->integer('author_id')->unsigned();
            $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {

    }
}

Book Model

  <?php

    namespace App;

    use IlluminateDatabaseEloquentModel;

    class Book extends Model
    {
        protected $fillable =[
            'title','genres','synopsis','author_id'];

        public function author()
        {
            return $this->belongsTo(Author::class);
        }
    }

and its Book controller for request from client

     public function deleteBook($id)
   {
    $client = New GuzzleHttpClient();
       $apiRequest = $client->request('DELETE','http://localhost:8080/api/book/'. $id);

       return redirect()->route('book.index')->with('response', 'Delete book successfully');

   }



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-one-to-many-relation-delete-request-with-guzzle/
via Lzo Media

Saturday, February 24, 2018

Laravel 5.6 – Cascading, dependent dropdown — update edit form - development

Laravel 5.6 – Cascading, dependent dropdown — update edit form

I’m following this tutorial to make a cascading dropdowns in Laravel:
http://www.codovel.com/client-side-image-preview-before-upload-javascript-jquery.html

Everything works fine for creating a record, but I’m stuck when I want to update/edit the record.
Can anyone give a tip, please?
Thank you,



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-5-6-cascading-dependent-dropdown-update-edit-form/
via Lzo Media

Laravel middleware different method if no access token found - development

Laravel middleware different method if no access token found

I’m newbie for Laravel passport. What I want to achieve is able to verify whether there is access token pass in by user.

I want to call @index route when there are access token found,
call @indexTest route when no access token is found.

Do I have to create custom middleware for this case?
Thanks.

In api.php

/**
 * Category
 */
Route::resource('categoriesbranches', 'CategoryCategoryBranchController@index', ['only' => ['index']])->middleware('client.credentials');
Route::resource('categoriesbranches', 'CategoryCategoryBranchController@indexTest');

In CategoryBranchController.php

    // public function __construct()
    // {
    //     $this->middleware('client.credentials')->only(['index']);
    // }

    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        //different action
    }

    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function indexTest()
    {
        //different action
    }


from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-middleware-different-method-if-no-access-token-found/
via Lzo Media

Some concerns on online exam system - development

Some concerns on online exam system

I’m recently developing online exam module for school management system. And i have some concerns about the following things:

  • When user accidentally close the browser, or logout his or her account while taking the exam, how i supposed to save the current answers of the exam for continue the exam if user login back or open the url which is supposed to continue exam one’s recent exam, within the time? Which one is better option, local or session storage, cache, temporary table, or just a table? Any advice or best practice? 🙂
  • In case user can continue the exam from different location but can’t continue or take the exam from two or more locations at same time, how i’m supposed to catch if user is attempting to take exam at two or more different location at same time while user is already logged in and taking the exam?

I’m using mysql, laravel, angular to build my module.
I would really appreciate any advice.

I am not a native speaker of English so guys, please, try to understand. 🙂



from Laravel Questions and Answers https://laravelquestions.com/html/some-concerns-on-online-exam-system/
via Lzo Media

getting brands of products with discounts - development

getting brands of products with discounts

I try to make search in brands where thy have discounted products.

Discount Logic

Discount table will save product_id, and product has brand_id

What I want

  1. I need solution to get out brands of products that their id is saved in discount table and list them.
  2. After that I want to select each of those brands and show result of
    products which has discount and has this brand id.

Codes

here is how I get my discounted products:

$promotions = Discount::with('products')->Valid()->orderby('id', 'desc')->paginate(12);

This is my brands:

$brandspromotion = Brand::OfStatus('Active')->get();

here is my full code:

        // Index `Promotion` page (where all results are mixed from all brands etc.)
            public function promotions() {
                $promotions = Discount::with('products')->Valid()->orderby('id', 'desc')->paginate(12); // get all discounted products
                $options = Option::all(); // for my sidebar only
                $brands = Brand::OfStatus('Active')->get(); // for my sidebar only



                $brandspromotion = Brand::OfStatus('Active')->get();
//this has to be change to some query in order to only get brands of discounted products
//result of this i will use in drop-down select box.




                return view('front.promotions', compact('promotions', 'options', 'brandspromotion', 'brands'));
              }

    // this function will take care of chosen brand result
          public function brandspromotions($slug) {
            //
          }

any idea?

UPDATE

I changed my query to something like code below:

$promotions2 = Discount::with('products')->Valid()->orderby('id', 'desc')->get();
    foreach($promotions2 as $brandpro){
      $brand_id = $brandpro->products->brand_id;
    }
    $brandspromotion = Brand::OfStatus('Active')
    ->where('id', '=', $brand_id)->get();

It is working but only gets 1 brand, something with my loop has to be wrong!

Update 2

I tried to use map here is my code:

$promotions2 = Discount::with('products')->Valid()->get();
    $grouped = $promotions2->map(function ($item, $key) {
      return $item->products->brand_id;
    });
    $grouped->all();
    // dd($grouped);
    $brandspromotion = Brand::OfStatus('Active')
    ->where('id', '=', $grouped)->get();

result is like:

Collection {#713 ▼
  #items: array:4 [▼
    0 => 2
    1 => 1
    2 => 2
    3 => 1
  ]
}

I suppose to get lenovo (id:1) and lg (id:2) but i only get lg.



from Laravel Questions and Answers https://laravelquestions.com/php/getting-brands-of-products-with-discounts/
via Lzo Media

Get rid of index.php in URL Laravel - development

Get rid of index.php in URL Laravel

Hi,

I’m new to Laravel and installed it just successfully. But i having a problem. When i use:

php artisan make:auth 

Its creates the register and login page but i can only access it if it include index.php in the URL. I want to get rid of the index.php in the URL. Any knows how to fix this?

 GNU nano 2.5.3 File: .htaccess <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> 

Config file https://ghostbin.com/paste/u95kr

I’m using Ubuntu 16.04 (digitalocean)

submitted by /u/TristanMagnus
[link] [comments]



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/get-rid-of-index-php-in-url-laravel/
via Lzo Media

How to save multiple addresses field for a single user in eloquent - development

How to save multiple addresses field for a single user in eloquent

I wanna save and retrieve multiple addresses for a user, also have created multiple address field using JQuery

public function store(Request $request)

{
    $user = new User();
        $data = $this->validate($request, [
      //User detail
            'name' => 'required',
            'gender' => 'required',
            'phone' => 'required',
     //Address fields
            'city' => 'required',
            'state' => 'required',
            'country' => 'required'
        ]);

}

I can get input for request from blade as below
{“name”:”name”,”gender”:”Male”,”phone”:”999999999″,”city”:”city1″,”state”:”state1″,”country”:”India”,”city”:”city2″,”state”:”state2″,”country”:”India”}

Now here I wanna save this —-> city1, state1, india and city2, state2, india into different column in single table.



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-save-multiple-addresses-field-for-a-single-user-in-eloquent/
via Lzo Media

Processing Conflict: php72u-common-7.2.2-1.ius.centos7.x86_64 conflicts php-common < 7.2.2-1.ius.centos7 - development

Processing Conflict: php72u-common-7.2.2-1.ius.centos7.x86_64 conflicts php-common < 7.2.2-1.ius.centos7

I am setting a new web server(will host laravel application) and I followed the tutorials from here.

Everything works fine until I tried executing this command : yum -y install phpMyAdmin, I got an error below:


--> Processing Conflict: php72u-common-7.2.2-1.ius.centos7.x86_64 conflicts php-common < 7.2.2-1.ius.centos7
--> Finished Dependency Resolution
Error: php72u-common conflicts with php-common-7.1.14-1.el7.remi.x86_64
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest

Then, when I try to execute this command: nano /etc/httpd/conf.d/phpMyAdmin.conf, the phpMyAdmin.conf file is empty.



from Laravel Questions and Answers https://laravelquestions.com/laravel/processing-conflict-php72u-common-7-2-2-1-ius-centos7-x86_64-conflicts-php-common-7-2-2-1-ius-centos7/
via Lzo Media

Regular Expression is not working properly in laravel validation - development

Regular Expression is not working properly in laravel validation

I am using laravel validation. I want to take input and store data like this.
111-111-111. This is the demo value. There should be 3 number in each part.
Here is my validation rule

'id'  => 'required|regex:/[0-9]{3}-[0-9]{3}-[0-9]{3}/|unique:info',

First two part working perfect but in last part I can take more than 3 number. I mean if input is 111-111-11111 it take the input.



from Laravel Questions and Answers https://laravelquestions.com/laravel/regular-expression-is-not-working-properly-in-laravel-validation/
via Lzo Media

How to pass a collection created without a model to a view file? - development

How to pass a collection created without a model to a view file?

$mp=DB::table('miip')->get();
$mc=DB::table('mii')->get();
$mpc=collect([]);
foreach($mp as $post1)
{ foreach($mc as $post2)
  {
  if($post1->mipname==$post2->miname)
    {
      if($post1->mipvalue!=$post2->mivalue)
    {
      $mpc->name=$post1->mipname;
      $mpc->pvalue=$post1->mipvalue;
      $mpc->cvalue=$post2->mivalue;
    }
  }
 }
 } 
 return view('crud/ckv', compact('mpc'));

view file(ckv.blade.php)

 <table class="table table-striped">
      @foreach($mpc as $post)
        <tr>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        @endforeach
  </table>

web.php

 Route::get('/mischkp', 'CRUDController@mischkp');

The program checks for changed values of products over a day. The program is working but the view file is not accepting mpc.



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-pass-a-collection-created-without-a-model-to-a-view-file/
via Lzo Media

Event not sending in real time laravel - development

Event not sending in real time laravel

I have situation.
I have event:

class MessageIsSeen implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $conversation;
    public $user;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Conversation $conversation, User $user)
    {
        $this->conversation = $conversation;
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return IlluminateBroadcastingChannel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('conversation.'.$this->conversation->id.'.'.$user->id);
    }}

In controller:

public function setMessagesSeen(Conversation $conversation) {

    $user = User::find(Auth::id());

    //$readed = Chat::conversations($conversation)->for($user)->readAll();

    //if($readed)
    broadcast(new MessageIsSeen($conversation, $user));

    //return json_encode(['lol']);
}

In app.js:

methods: {
    seenMessage() {
        //if(this.message.length != 0) {
            axios.post('/setMessagesSeen/' + this.convId)
            .then( response => { $('li').removeClass('unread'); }) 
            .catch( response => { console.log(response) } )
        //}
    }, //working. Send request to controller setMessageIsSeen
    mounted() {
        Echo.private('conversation.'+this.convId+'.'+ this.user.userId)
            .listen('MessageIsSeen', (e) => {
                console.log(e);
            });
    }

channels:

Broadcast::channel('conversation.{conversation_id}.{user_id}', function($user, $conversation_id, $user_id) {
    return $user;
});

In mounted event not listen. In console I didn’t have messages about event. In pusher I see messages only that channel: conversation.1.1 subscribed, occupied e.t.c. But messages about event MessageIsSeen – not. Please help fix it. In channels.php I have event.



from Laravel Questions and Answers https://laravelquestions.com/php/event-not-sending-in-real-time-laravel/
via Lzo Media

Friday, February 23, 2018

Laravel 5.6.4 Released - development

Laravel 5.6.4 Released

Laravel 5.6.4 is now released, with highlights including support for callbacks as custom log drivers and a Blade method for include aliases.

Visit Laravel News for the full post.

The post Laravel 5.6.4 Released appeared first on Laravel News.



from Laravel Questions and Answers https://laravelquestions.com/news/laravel-5-6-4-released/
via Lzo Media

Thursday, February 22, 2018

i stumbled upon property item does not exist while working on laravel, - development

i stumbled upon property item does not exist while working on laravel,

@foreach($package->items as $item)
<option value=""></option>
@endforeach

but when i do this it fetches the data correctly but it has all the attributes,all i need is the item name,

@foreach($package as $item)                 
 <option value=""></option>             
@endforeach



from Laravel Questions and Answers https://laravelquestions.com/php/i-stumbled-upon-property-item-does-not-exist-while-working-on-laravel/
via Lzo Media

Validate laravel date firmat with Y-m-dTH:i:s - development

Validate laravel date firmat with Y-m-dTH:i:s

I’m building an API and it should accept date and time value as the format of Y-m-dTH:i:s. The specialty of this that there’s T in the middle between date and time.

So, how to write validation rule to check this ?

'start_at' => 'required|date_format:Y-m-d H:i:s'

This is what I currently have.



from Laravel Questions and Answers https://laravelquestions.com/php/validate-laravel-date-firmat-with-y-m-dthis/
via Lzo Media

cURL error 7: Failed to connect to maps.googleapis.com port 443 - development

cURL error 7: Failed to connect to maps.googleapis.com port 443

I got following Error when get Distance between two places in Laravel. i use guzzlehttp/guzzle package to get Google Map api response. i previously declare use GuzzleHttpClient; How to solve this Issue.

Error : cURL error 7: Failed to connect to maps.googleapis.com port
443: Network is unreachable (see
http://curl.haxx.se/libcurl/c/libcurl-errors.html)

$pickupaddress = urlencode($frmplace);
$deliveryaddress = urlencode($destplace);
$client = new GuzzleHttpClient();

$disrequest = $client->get('https://maps.googleapis.com/maps/api/distancematrix/json?origins='.$pickupaddress.'&destinations='.$deliveryaddress.'&mode=driving&key=ASESdsfsdfsdfdsfdf')->getBody();

$disjsondecode = json_decode($disrequest);
$tripdistance = $disjsondecode->rows[0]->elements[0]->distance->text;



from Laravel Questions and Answers https://laravelquestions.com/laravel/curl-error-7-failed-to-connect-to-maps-googleapis-com-port-443/
via Lzo Media

Doctrine Laravel not closing connections after trying to close them - development

Doctrine Laravel not closing connections after trying to close them

So there is (or at least was, but the issue for me persists) o problem with amount of connections to MySql DB when running tests that use DB or many php processes (workers that have several connections to DB).

After a process is finished it leaves some hanging connections to DB and soon you hit Too many connections exception.

There is one main solution – to close them manully in the code like so:

$doctrine = $this->getDoctrine();
    foreach ($doctrine->getManagers() as $name => $entityManager) {
        $entityManager->close();
        $connection->close();
    }

Well in my case, since i use Laravel-Doctrine ORM:

foreach ($this->managerRegistry->getManagers() as $manager) {
        $manager->getConnection()->close();
        $manager->close();
    }

However my code snipped just simply does not work. When i check the amount of connections through MySql client SHOW PROCESSLIST; the connections are still growing.

I even tried to put “closing actions” in a recursive function to exit only when the connection is really closed. Yes, i am totally aware that this approach is hacky and dumb but im trying everything to close those connections.

Heres the snippet:

private function terminate() {

    echo "Amount of managers: " . count($this->managerRegistry->getManagers());

    foreach ($this->managerRegistry->getManagers() as $manager) {
        $manager->getConnection()->close();
        $manager->close();
    }

    echo "Amount of connections: " . count($this->managerRegistry->getConnections());

    foreach ($this->managerRegistry->getConnections() as $connection) {
        $connection->close();
    }

    gc_collect_cycles();

    if (count($this->managerRegistry->getManagers()) > 0 || count($this->managerRegistry->getConnections()) > 0) {
        sleep (1);
        $this->terminate();
    }
}

What is going on? What do i do?



from Laravel Questions and Answers https://laravelquestions.com/php/doctrine-laravel-not-closing-connections-after-trying-to-close-them/
via Lzo Media

Retrieve data from the database using Eloquent between two dates - development

Retrieve data from the database using Eloquent between two dates

I’m having trouble retrieving data from the database using Eloquent. I am trying to retrieve all data between two dates (created_at field).

I’ve done this:

 public function search(Request $request){
        $start_date  = $request->get('start_date');
        $end_date = $request->get('end_date');

        $getinfo =  DB::table('media')
            ->join('content_forms', 'media.id', "=", 'content_forms.media_id')
            ->whereBetween('Date_Occured',[$start_date, $end_date])
            ->get();
        dd($getinfo);
    }



from Laravel Questions and Answers https://laravelquestions.com/php/retrieve-data-from-the-database-using-eloquent-between-two-dates/
via Lzo Media

Using whereInStrict() in laravel 5.5 - development

Using whereInStrict() in laravel 5.5

I tried using whereIn() in my project but because of its loose comparison it considered a value ‘1gb’ as integer. So as per the documentation I used whereInStrict().

$spec['vals'] = ['1 gb', '2gb', '8gb']; // array created by explod()     
ProductSpecification::whereInStrict('value', $spec['vals'])->get();

But the creates sql query like “Select * from product_specifications where in_strict = ‘value’ “, thus giving an error. What to do? Am I using it wrong?

I’m kinda new to laravel.



from Laravel Questions and Answers https://laravelquestions.com/php/using-whereinstrict-in-laravel-5-5/
via Lzo Media

Laravel Forgot Password (Reset Password) - development

Laravel Forgot Password (Reset Password)

I have a Laravel app, and the password reset feature is needed. How can I flash a session message after the email is sent to the user or after clicking the submit button?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-forgot-password-reset-password/
via Lzo Media

Session expired error when attempting to login after session lifetime runs out - development

Session expired error when attempting to login after session lifetime runs out

Currently the user is redirected to the login page is the session is expired. If the user stays on the login page for too long, past the session lifetime of 120 minutes, it will still allow them to attempt a login but they’ll receive a session expired error on submission. They then need to go back and try logging in again.

Is there a way to make sure that the session is refreshed on login submission? Or keep logged out sessions indefinite?



from Laravel Questions and Answers https://laravelquestions.com/laravel/session-expired-error-when-attempting-to-login-after-session-lifetime-runs-out/
via Lzo Media

How to create/store and update associative models - development

How to create/store and update associative models

I was wonder what the proper way was to create/store and update associative models.
Where I work we don’t use laravel but we basically do the following

$formData = [ 'first_name', 'last_name', 'invoice_address' = [ 'first_name', 'last_name', ] 

So we have formdata for an order for example. Where I work we will create an order in the OrdersController and after succesfully saving it we will create an invoice_adress also in the OrdersController.
I read regularly that you should not deviate from the basic crud flow, so in my mind it makes sense to create an order in the OrdersController and after succesfully saving that, create an invoice_address in the InvoiceAddressesController and associate it with the newly created order.
So basically I’m wondering what the proper way is and how to achieve this in laravel?

submitted by /u/NotARandomRedditor
[link] [comments]



from Laravel Questions and Answers https://laravelquestions.com/rlaravel/how-to-create-store-and-update-associative-models/
via Lzo Media

what’s the meaning/function for ‘??’ in php/laravel [duplicate] - development

what’s the meaning/function for ‘??’ in php/laravel [duplicate]

This question already has an answer here:

I found out that laravel use ‘??’ symbol in php

the example code is

  $this->connections->connection($config['connection'] ?? null)

What does ‘??’ mean ?



from Laravel Questions and Answers https://laravelquestions.com/php/whats-the-meaning-function-for-in-php-laravel-duplicate/
via Lzo Media

Wednesday, February 21, 2018

5 Laravel Helpers to Make Your Life Easier - development

5 Laravel Helpers to Make Your Life Easier

There are a ton of helper methods in Laravel that make development more efficient. If you work with the framework, I encourage you to see what helpers you can introduce in your day-to-day work. In this blog post, I’d like to point out a few of my favorites.

Visit Laravel News for the full post.

The post 5 Laravel Helpers to Make Your Life Easier appeared first on Laravel News.



from Laravel Questions and Answers https://laravelquestions.com/news/5-laravel-helpers-to-make-your-life-easier/
via Lzo Media

Internal Error 500: Hosting our latest Laravel 5.1 site on good working Vagrant/Homestead environment - development

Internal Error 500: Hosting our latest Laravel 5.1 site on good working Vagrant/Homestead environment

Configuration Development system

  • Laravel 5.1
  • Good working Vagrant/homestead on windows 10.
  • V1 Production Laravel site working on Vagrant/homestead (non-responsive)
  • V2 production Laravel NOT working on Vagrant/homestead (responsive)

The Steps to narrow the problem:

Part 1 – The basics

  1. Import SQL file with PhpMyAdmin
  2. I have added or changed all the necessary steps (URL, homestead.yaml, hostfile ect)
  3. I have a Working fresh Laravel 5.1 installation

Part – 2 The Migration

  1. Imported a new database with phpMyAdmin
  2. Removed the fresh installation
  3. Copy the new “production environment”
  4. Changed the .env file with the required database information
  5. Load site and BAM an Laravel error “Houston we have got a problem Internal 500 message”

Part – 3 Done so far fixing the problem

  1. Artisan clear cache will make it worse
  2. Removed everything and installed a fresh 5.1 Laravel environment
  3. Copy the folders 1 by one and when I copy the APP directory it will result in an “Internal error 500”

Part – 4 Conclusion

We have a good working vagrant/homestead environment and it goes wrong when I am migrating the new production site to this configuration. The difference between V1 and V2 is that V1 (working on vagrant/homestead) is a non-responsive site and V2 is the same site but completely responsive.

Any tips on how to solve this issue



from Laravel Questions and Answers https://laravelquestions.com/php/internal-error-500-hosting-our-latest-laravel-5-1-site-on-good-working-vagrant-homestead-environment/
via Lzo Media

elasticsearch – scout:import doesn’t import second model - development

elasticsearch – scout:import doesn’t import second model

I am trying to import items and tags but it always imports the first one and ignores the second one (doesn’t matter which one: if I import an item it will not import a tag and vice versa)

mappings: {
    items: {
        properties: {}
    }
}

or

mappings: {
    tags: {
        properties: {}
    }
}

In both models I am using Searchable and toSearchableArray function…

I am using scout and tamayo/laravel-scout-elastic latest version

so mapping doesn’t work for the second model



from Laravel Questions and Answers https://laravelquestions.com/php/elasticsearch-scoutimport-doesnt-import-second-model/
via Lzo Media

Laravel request unknown number of validate parameters - development

Laravel request unknown number of validate parameters

I have 3 parameters that I send through request body.
At least one of them is necessary, others are optional, but it could be all 3 that would be send.

How should I validate this data? sometimes rule helps with optional parameters but how do I define that at least 1 is required?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-request-unknown-number-of-validate-parameters/
via Lzo Media

Trying to get property of non-object in VerifyCsrfToken.php (line 156) Laravel 5.4 - development

Trying to get property of non-object in VerifyCsrfToken.php (line 156) Laravel 5.4

I have a Shell Script that execute a route API in my Laravel Application. However, when it execute it, I have a error from Token.

Trying to get property of non-object
in VerifyCsrfToken.php (line 156)

The route is to http://localhost:8000/api/soap.
In SoapController, I redirect to other route inside to the application:

return redirect('/control_fich/'.$id_user.'/'.$date_utc);

The route is:

Route::get('control_fich/{id}/{date}','ControlFichController@index');

And I put this route how a except in the middleware VerifyCsrfToken.php

protected $except = [
    'dropdown',
    'control_fich/{id}/{date}',
];

But the error continues. What I have to do to execute an internal Controller from an API Controller?

Thanks



from Laravel Questions and Answers https://laravelquestions.com/php/trying-to-get-property-of-non-object-in-verifycsrftoken-php-line-156-laravel-5-4/
via Lzo Media

Laravel 5.5 groupBy with sum and first option - development

Laravel 5.5 groupBy with sum and first option

I have a table with some same id so I display them groupBy option with sum. I have many column like id, item_name, rate, quantity, value Here is my code.

$orders = Order::where('item_id', $id)
    ->where('delivery_status', 1)
    ->groupBy('item_id')
    ->selectRaw('sum(quantity) as quantity, sum(value) as value, item_id')
    ->pluck('item_id','quantity', 'value');

By this I got three column with id and quantity and value with sum. My problem is that I also want to display other column like item_name, rate, delivery_status etc. and I don’t want to sum them like rate. How can I display them? I can groupBy also with item_name and it works but can not group with rate because other items may also have same rate.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-5-5-groupby-with-sum-and-first-option/
via Lzo Media

Laravel data_get helper has different behavior for array and object - development

Laravel data_get helper has different behavior for array and object

$array = ['key' => null];

echo data_get($array, 'key', 'default') // Result was default
$array = (object) $array;
echo data_get($array, 'key', 'default') // Result was null 

Is there any specific reason it was done like this or arrays and objects?

Laravel doc ref



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-data_get-helper-has-different-behavior-for-array-and-object/
via Lzo Media

Apply search on Multidimensional array in Laravel - development

Apply search on Multidimensional array in Laravel

How can I search through multiple arrays. I am making custom search functionality for datatable. How can I do that?
I am stuck how can I search and find amongst array and return the array.

$records = Array
(
    [0] => Array
        (
            [0] => 28
            [1] => http://198.58.98.34:4600/uploads/item/priority_images-1519195620005Item1.png
            [2] => Currency
            [3] => Demo1
            [4] => Hello
            [5] => 980
            [6] => 2018-02-21T06:47:15.264Z
        )

    [1] => Array
        (
            [0] => 27
            [1] => http://198.58.98.34:4600/uploads/item/1519120091372-filewinter_is_here_game_of_thrones_hd-1920x1080.jpg
            [2] => coins212
            [3] => Demo2
            [4] => Hello1
            [5] => 54564
            [6] => 2018-02-21T06:38:04.053Z
        )
);

$search = $request['search']['value'];

I tried using array_column but it was not working.
How Can I search and return the searched data.?



from Laravel Questions and Answers https://laravelquestions.com/php/apply-search-on-multidimensional-array-in-laravel/
via Lzo Media

Images Upload According To Category - development

Images Upload According To Category

Laravel Version: 5.6.0
Voyager Version: dev-1.x-dev
PHP Version: 7.2.1

Description:

I want to upload multiple images to different folders depending on the image category (ex Car / Van). Inside of each image category folder there should be folders for thumbs, medium and cropped. And also the name of the uploaded file should be changed to (category name-timestamp.extension). I googled for this and also looked at videos in youtube without any luck. Can someone help me with this.



from Laravel Questions and Answers https://laravelquestions.com/laravel/images-upload-according-to-category/
via Lzo Media

Need insurance api for website integration [on hold] - development

Need insurance api for website integration [on hold]

Insurance Api integration:
I am working on insurance portal where user get detail about insurance policy. Now i need to integrate insurance api for fetching insurance detail and if user interested then he/she can buy that policy.I couldn’t found any links either it is paid or free.Please suggest me where i can get api for insurance.



from Laravel Questions and Answers https://laravelquestions.com/php/need-insurance-api-for-website-integration-on-hold/
via Lzo Media

inconsistent email format of html input field with laravel email validation - development

inconsistent email format of html input field with laravel email validation

In my blade file i have a html form for user in which input field email have type email. But i think it provide inconsistent email format validation. example it show abc@xyz and abc@xyz.com both are correct email address but in my controller, validator method return me invalid email format for abc@xyz. How can i resolve this issue???

In my blade file:

<input type="email" name="email" value="">

And in my controller:

$validator = Validator::make($request->all(), [
     'email'       => 'email|unique:table_name,col_name',
    ],[
     'email.unique' => 'email is already in used',
   ]);

if ($validator->fails()) {
    return redirect()->back()->withInput($request->all())->withErrors($validator);
  }



from Laravel Questions and Answers https://laravelquestions.com/html/inconsistent-email-format-of-html-input-field-with-laravel-email-validation/
via Lzo Media

Tuesday, February 20, 2018

Polacode – Easily Share Code Screenshots from VS Code - development

Polacode – Easily Share Code Screenshots from VS Code

Polacode is an extension for VS Code that allows you to quickly create awesome screenshots of your code for sharing with others. What makes this unique is it keeps your existing theme and fonts and puts it in a nice layout.

Visit Laravel News for the full post.

The post Polacode – Easily Share Code Screenshots from VS Code appeared first on Laravel News.



from Laravel Questions and Answers https://laravelquestions.com/news/polacode-easily-share-code-screenshots-from-vs-code/
via Lzo Media

Testing Length Validation in Laravel - development

Testing Length Validation in Laravel

I thought it might help people new to the Laravel framework and testing, to walk through how to test length validation. When I say length validation, I mean the constraints of length that you might want to put on a string field.

For example, let’s say that we wanted to limit the length of a user’s real name to 50 characters; or if we restrict the email address to the database column length of 255. Along with the database constraints, we should add validation constraints to the controller when creating and updating records.

Visit Laravel News for the full post.

The post Testing Length Validation in Laravel appeared first on Laravel News.



from Laravel Questions and Answers https://laravelquestions.com/news/testing-length-validation-in-laravel/
via Lzo Media

LaraTalent – A New Way to Hire and Get Hired - development

LaraTalent – A New Way to Hire and Get Hired

LaraTalent is a brand new take on getting you the best job or the best employee. LaraTalent turns the job search process on its head. As part of a hand-selected group presented to employers, YOU get their full attention and YOU select the employers you’d like to interview with. When employers compete, you win. — …

Visit Laravel News for the full post.

The post LaraTalent – A New Way to Hire and Get Hired appeared first on Laravel News.



from Laravel Questions and Answers https://laravelquestions.com/news/laratalent-a-new-way-to-hire-and-get-hired/
via Lzo Media

Failed verification of login - development

Failed verification of login

I am trying to verify my users who log into the system. I have used hashed passwords to store the passwords. When I try to verify the users, I get an error as follows:

strlen() expects parameter 1 to be string, array given

I have searched various ways of solving this issue but I can’t find a way.

Here is my code.

controller.php

public function logs_in(Request $request){
    $email = $request->input('email');
    $password = $request->input('password');


    $hashedPassword = DB::select('select password from users where email = ?', [$email]);


    if(Hash::check($password, $hashedPassword)){
        $request->session()->put('success');
        return redirect()->route('admin');
    } else {
        return redirect()->route('login')->with('login_error', 'Invalid 
        credentials entered');
    }
}

What could possibly be wrong?



from Laravel Questions and Answers https://laravelquestions.com/php/failed-verification-of-login/
via Lzo Media

Laravel eloquent not getting the results - development

Laravel eloquent not getting the results

I have a laravel project and I don’t see where is the bug here.

I have a products table with a “low_stock_warning” integer field and a “units_stock” integer field.

I want to get the products with a “units_stock” less than “low_stock_warning“, so I have

$stock_warning = Product::whereRaw('units_stock <= low_stock_warning')
    ->select('id')
    ->get();

The result mysql is:

select `id` from `products` where units_stock <= low_stock_warning

If I execute it in my database directly I get one product. Ok, but Eloquent tells me that $stock_warning is an empty array…

What I’m missing here ?

Thanks!

enter image description here

EDIT 1:

I’ve tried with:

$stock_warning = Product::whereColumn('units_stock', '<=', 'low_stock_warning')->pluck('id');

print_r($stock_warning);

And the result is:

IlluminateSupportCollection Object ( [items:protected] => Array ( ) )



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-eloquent-not-getting-the-results/
via Lzo Media

Laravel view update when database is changed from another app - development

Laravel view update when database is changed from another app

i do not have much experience in Laravel and i need to make a Laravel view live update. The case scenario is this one: I have my Laravel app that communicates for CRUD operations with database. This app calls a script that make some operations that take a while(more than a opened connection). When the script operations are finished, database is updated and i have to intercept that event to change the view in Laravel from proceeding to done. I found some hints about using socket io but i was thinking that maybe Laravel has something already cooked for it.Does anyone know how this can be done?enter image description here



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-view-update-when-database-is-changed-from-another-app/
via Lzo Media

Amazon Web Services get Search() response needs try catch continuously - development

Amazon Web Services get Search() response needs try catch continuously

I´m using Amazon Web Services in Laravel app. I created this page:
https://frikinow.com/libros-frikis

If you reload the page sometimes works and sometimes does not.

this is because the amazon method needs to be continuously put into a try catch

public function getLibrosFrikis() {

        # string $category, string $keyword = null, int $page = 1
        try {
            $page1  = AmazonProduct::search('Books', 'libros,frikis' , 1);

            $page2  = AmazonProduct::search('Books', 'libros,frikis' , 2);

            $page3  = AmazonProduct::search('Books', 'libros,frikis' , 3);


            $articles = collect([$page1['Items']['Item'],$page2['Items']['Item'],$page3['Items']['Item']])->flatten(1);


            $params = array(

                'articles' => $articles,
            );

        } 
        catch(ServerException $e) {
        }


        return view('pages.ecommerce.libros_frikis', $params);
      }

I managed to put it in the WebController but I don’t know how to capture the exception in Blade view HTML:

<div class="row-flex-shrink row-flex-wrap">

        @foreach($articles as $article)



            <div class="col-sm-4 col-md-3" style="margin-bottom: 16px;">
                <a href="" target="_blank" rel="nofollow">
                    <div class="item amazon-item">
                        <img src="" alt="" class="img-responsive">
                        <div class="title"></div>
                        <div class="btn btn-warning">ver precio</div>
                    </div>
                </a>
            </div>


        @endforeach

    </div>

How can I control this?



from Laravel Questions and Answers https://laravelquestions.com/php/amazon-web-services-get-search-response-needs-try-catch-continuously/
via Lzo Media

How To Solve This Trying to get property of non-object Error In Laravel - development

How To Solve This Trying to get property of non-object Error In Laravel

I’m creating a web site. And I have created a registration page. I want to update my details.

But, It gives me this error and I have also uploaded a picture of errors below. –
Error Picture

ErrorException (E_ERROR) Trying to get property of non-object (View:
D:wamp64wwwFinalProjectresourcesviewsAdminUpdate.blade.php)

I used dd($edd); and it gave me correct details. But, when I try with below codes it gives me that above error.

How can I Fix this ??

Here is my AdminPanel.blade.php

<table class="table table-bordered">

<tr>
<td> Name </td>
</tr>


@foreach($data as $value )
<tr>
<td>  </td>
<td> <a href="edit/"><input type="submit" name="update" value="Update" class="btn-primary"></a> </td>
</tr>
@endforeach
</table>

Here is my AdminPanelController.php

public function edit($id)
{
$edd = User::find($id);
//dd($edd);
      return view('AdminUpdate', ['edd' => $edd]);

}

    public function adminedit($id, Request $request, User $user)
{
    // Add Validation

    $users = $user->find($id);
    $users->username = $request->get('username');
    $users->email = $request->get('email');
    $users->save();

    return redirect()->back();
}

Here is my AdminUpdate.blade.php

<form action="edit/" method="post" enctype="multipart/form-data">

    
    

  <div class="form-group">
    <label>Username : *</label>
    <input type="text" class="form-control" name="username" value="" placeholder="Enter Your Username" required>
  </div>

    <div class="form-group">
    <label>Email : *</label>
    <input type="email" class="form-control" name="email" value="" placeholder="Enter Your Username" required>
  </div>

  <div class="form-group">
    <label>Password : *</label>
    <input type="password" class="form-control" name="password" value="" placeholder="Enter Your Password" required>
  </div>

  <div class="form-group">
    <label>Upload Profile Picture :</label>
    <input type="file" class="form-control-file" name="file_img" aria-describedby="fileHelp">
    <small id="fileHelp" class="form-text text-muted">If U Want , U Can Skip Upload A Profile Picture</small>
  </div>

  <input type="submit" class="btn btn-primary" value="Update User">
                    </form>

Here are my Routes.

Route::get('/edit/{id}', 'AdminPanelController@edit');

Route::post('/edit/{id}', 'AdminPanelController@adminedit');



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-solve-this-trying-to-get-property-of-non-object-error-in-laravel/
via Lzo Media

php (laravel) short hand for creating an array with elements has id property - development

php (laravel) short hand for creating an array with elements has id property

I want to create an array like this

$a = [ 
  ['id' => 1],
  ['id' => 2],
  ['id' => 3],
  ['id' => 4],
   ....
]

just like array_fill but with id property for each element

I known I could do it by loop and map function but I wonder if there is a short hand for this. I’m using php laravel framework. thanks in advance



from Laravel Questions and Answers https://laravelquestions.com/php/php-laravel-short-hand-for-creating-an-array-with-elements-has-id-property/
via Lzo Media

Laravel: Can I get DB request as indexed array - development

Laravel: Can I get DB request as indexed array

I’ve met a problem wit Laravel DB query.
I have to use something like:

$priceList = DB::select("exec dataBase.dbo.PRICELIST ?", [$id]);

But I can’t directly access server.
As it tries to return associative array it fails to return anything.
Does enyone know how to return indexed array from this in Laravel?

EDIT:

I’m receiving data from stored procedure not table

Thanks for any help! 🙂



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-can-i-get-db-request-as-indexed-array/
via Lzo Media

count with group on eloquent laravel - development

count with group on eloquent laravel

Hi i have make this query on oracle:

select count(*), queue
from cases
where queue not in ('OPBO_SA_Work-in-Prog','OP_AD_WIN_TECH')
group by queue

this is the result:

18  OP_AD_WIN_ACTIVATION
18  OP_AD_WIN_HARDWARE
4   OP_AD_WIN_FIBER
37  OPBO_WIN_Fiber_pend_i
8   OP_AD_WIN_RELOCATION
47  OPBO_WIN_Act_pend_i

i wana make the same on laravel i try this:

  'total' => $this->cases->select('queue')->whereNotIn('queue',
['OPBO_SA_Work-in-Prog','OP_AD_WIN_TECH'])->groupBy('queue')->count(),

the result is
18 ( only the first number )



from Laravel Questions and Answers https://laravelquestions.com/laravel/count-with-group-on-eloquent-laravel/
via Lzo Media

How to populate Mailchimp Lists in drop down on selecting Mailchimp option - development

How to populate Mailchimp Lists in drop down on selecting Mailchimp option

I want to show Mailchimp Lists when I click Mailchimp option from drop down I have already make API call to get lists from mailchimp now I want to populate this lists on drop down when I click Mailchimp from drop down.

My Html View:

<div class="new-intergrtain-sec clearfix">
    <div class="form-group clearfix">
        <label class="controllabel" for="select">Mailing List Integration</label>
        <select class="slct-currncy required" id="select">
            <option value="">--- Select Integration ---</option>
            <option value="1">MailChimp</option>
        </select>
    </div>
    <div class="form-group clearfix">
        <label class="control-label" for="select2">Select Email Lists</label>
        <select class="slct-currncy required" id="select2">
            <option value="4"></option>
            <option value="5">MailChimp</option>
        </select>
    </div>
</div>

My Controller where I am getting listing from mailchimp

public function getLists(Request $request)
{
    $user_id = $request->user()->id;
    $apikey = DB::table('user_mlc_mailchimp')->where('user_id','=', $user_id)->value('api_key');
    if($apikey){
        $mc = new MailChimp($apikey);
        $mailchimp_ping = $mc->get('lists',['fields' => 'lists.id,lists.name', 'count' => 50]);
        $mailchimp_ping = ['status' => 1, 'message' => 'Lists Found!', 'dataArray' => $mailchimp_ping];
        return Response::json($mailchimp_ping, 200);

    }

    else {
        $errorResponse = [
            'message' => 'Lists not found!',
            'error' => '401'
        ];
        return Response::json( $errorResponse);
    }
}

My Route is :

Route::get('lists', 'ApiController@getLists');

From these I am getting all the lists available on mailchimp with the required get route which I mentioned.
now I want to populate this on my drop down in my HTML view which I have shared with you and my HTML link is:

http://localhost:8000/New-Sale-Page

and its route :

$router->get('/New-Sale-Page', function () use ($router) {
    return view('add-new-sale-page'); 
});

I have shared all the possible links from which u can help me I just want to show the mailchimp listing from drop down when I click mailchimp option,

Any help would be highly appreciated!



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-populate-mailchimp-lists-in-drop-down-on-selecting-mailchimp-option/
via Lzo Media

TinyMCE Remove Inserted Image Prefix? - development

TinyMCE Remove Inserted Image Prefix?

I am using TinyMCE Laravel File Manager but Im having an issue whenever I add images. Photos I save are saved at public_html/photos, but when I add the images to the tinyMCE editor using Insert > Image. The editor shows a broken image since the src provided has a prefix of laravel-filemanager showing as

src="http://localhost:8000/laravel-filemanager/photos/user_icon_add.png"

Instead of

src="http://localhost:8000/photos/user_icon_add.png"

How do I remove the laravel-filemanager prefix for photos that I add?

Here are some configs of my lfm.php

'url_prefix' => 'laravel-filemanager',
'base_directory' => 'public_html',
'images_folder_name' => 'photos',
'files_folder_name' => 'files',
'shared_folder_name' => 'shares',
'thumb_folder_name' => 'thumbs',

Here’s my tinyMCE js config

var editor_config = {
        path_absolute: "/",
        selector: "textarea",
        plugins: ["advlist autolink lists link charmap print preview hr pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen", "insertdatetime nonbreaking save table contextmenu directionality", "emoticons paste textcolor colorpicker textpattern"],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link",
        style_formats:
            [
                {
                    title: 'Bullet',
                    selector: 'ul',
                    classes: 'browser-default',
                }
            ],
        relative_urls: false,
        file_browser_callback: function (field_name, url, type, win) {
            var x = window.innerWidth || document.documentElement.clientWidth || document.getElementByTagName('body')[0].clientWidth;
            var y = window.innerHeight || document.documentElement.clientHeight || document.grtElementByTagName('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,
                resizeble: 'yes',
                close_previous: 'no'
            });
        }
    };
    tinymce.init(editor_config);



from Laravel Questions and Answers https://laravelquestions.com/php/tinymce-remove-inserted-image-prefix/
via Lzo Media