dimanche 31 décembre 2017

Laravel 5.4 ErrorException: Error while sending STMT_PREPARE packet in queue

I running my application in php laravel 5.4 framework, i used ratchet socket server for real time communication and queue for sending sms & email in between socket connection. sometimes i got an error like below,

ErrorException: Error while sending STMT_PREPARE packet. PID=6779 in /home/username/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php:319

Next Illuminate\Database\QueryException: Error while sending STMT_PREPARE packet. PID=6779 (SQL: select * from jobs where queue = default and ((reserved_at is null and available_at <= 1514718794) or (reserved_at <= 1514718704)) order by id asc limit 1 for update) in /home/username/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php:647

Due this error occurred after that socket server enters into following error

PDOException: SQLSTATE[HY000] [2002] No such file or directory in /home/username/project/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68

and socket server stops working due to this problem frequently occurred in production server. kindly help me to solve this issue asap. thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ErckD5
via IFTTT

Is there is way in laravel to call add profile page if there is no profile created else got to edit profile page?

I have created a profile but every time I add the profile it is added to the database but I need to edit it for the second time. Need help.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lyDaQR
via IFTTT

Laravel-5 whereHas Clouse dosen't work as expected

I have categories and products tables. They are related with Many to Many relationships.. I want to get products by categories but whereHas clause dosen't work

$products = Product::whereHas('categories',function ($query) use ($slug){
$query->where('category_name',$slug);
})->whereBetween('price',[100,200])->get();

Category Model;

public function products(){
return $this->belongsToMany('App\Product','category_product','category_id','product_id');
 }

So, what is my mistake in here ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cw9NqE
via IFTTT

Create a model with a required relationship

I'm trying to create a model that has a relationship which is required for the object to be valid. Querying this model should not return any results that are missing this relationship. It seems like global scopes are the best option for this scenario, however I've been unable to make this work. Am I doing something wrong? Perhaps there's a better way?

Here is a simplified version of the model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('has_details', function ($builder) {
            $builder->has('details');
        });
    }

    public function details()
    {
        return $this->hasOne(Details::class);
    }
}

And here is a one-to-many relationship method on another model.

public function cars()
{
    return $this->hasMany(Car::class);
}

Without the global scope, this code returns all related "cars", including ones without "details". With the global scope, no "cars" are returned. I want this code to only return "cars" with "details".

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lyTPnw
via IFTTT

installing larval valet in macOS Heigh Sierra

I'm having issues installing larval valet on macOS Heigh Sierra I already did the following steps.

  1. /usr/bin/ruby -e "$(curl -fsSL http://ift.tt/YQTuQh)" - this worked fine

  2. brew update - this worked fine

  3. brew install homebrew/php/php71 - this worked fine

  4. composer global require laravel/valet - this gives me command not found

I know I'm supposed to add it to the path but this command composer global require laravel/valet should work before I add the path



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2EkO05v
via IFTTT

Laravel - Import File Using Octet-Stream

I was curious if anyone has ever imported a file where the post parameters in the developer bar is formatted like below with the content-type being application/octet-stream?

Below is just the first couple of lines of the parameters sent in the post data:

-----------------------------24464570528145
Content-Disposition: form-data; name="RemoteFile"; filename="594.pdf"
Content-Type: application/octet-stream

%PDF-1.5
1 0 obj
<<
/Creator ()
/CreationDate (2

I'm curious how I would upload the file through the model controller and I'm hoping someone else here might have run across this sort of issue.

Thanks in advance -

Best -

Matt



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2C4jT0V
via IFTTT

Return a view with data after ajax call

I'm using Laravel 5.5 and jQuery.

I'm trying to return a view after an ajax call but with data and I don't find the solution.

JS:

$('#button-recommandations').on('click', function () {
    $.ajax({
        method: 'GET',
        url : 'recommandationsSeances',
        data : {
           'idSeance' : $(e.relatedTarget).data('seance')
        },
        xhrFields: { withCredentials: true },
        crossDomain : true
    });
});

PHP:

return view('listeRecommandations', [
     'recommandationAutresActiviteMemeDateHeure' => $recommandationAutresActiviteMemeDateHeure,
     'recommandationsMemeActiviteMemeHeure'      => $recommandationsMemeActiviteMemeHeure,
     'recommandationsMemeActiviteMemeDate'       => $recommandationsMemeActiviteMemeDate
]);

It is possible?

Thank's for help!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lA0gXx
via IFTTT

Laravel 5: Action not defined

I searched a little on the internet, I found some topics that spoke about this, but none about my problem specifically.

So my error:

Action App\Http\Controllers\Users@index not defined.

The controller Users:

<?php
namespace App\Http\Controllers;

use Illuminate\Routing\UrlGenerator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Input;
use App\Models\Users;
use Session;
use Validator;

    class Users extends Controller {

     protected $users;


     public function __construct(Users $users)
     {
             $this->users = $users;
     }

    public function index()
    {
        $data['limit']=$limit;
        $data['title']='Liste des Utilisateurs';

        $data['result']=$this->user->user_list($limit);

        return view('user_list', $data);
    }

The routes:

Route::get('users/{limit?}', function($limit = 0, Request $request)
{
  if(Auth::check()){
    return redirect()->action('Users@index');
  }else{
    $request->session()->flash('message', 'Vous devez vous connecter avant de pouvoir accéder à la plateforme.');
    return redirect('login');
  }
});

Best regards



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2EoTQmy
via IFTTT

Laravel class translator does not exist in a configuration file

Is there any way that allows inserting translatable value in configuration file in application?

I have a custom configuration file at config/fox-reports.php and I'm trying to set a translatable configuration value looks like the following:

return [
    'attrs' => [
       'Product' => __('Product Title')
    ]
] 

When I run php artisan config:cache the following error is generated:

In Container.php line 729:

  Class translator does not exist



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2DFwUhN
via IFTTT

Laravel redirect to correct path on missing routes

in my application when user enter this url as http://ift.tt/2Ch8cbl laravel show error as an

Sorry, the page you are looking for could not be found.

for that correct path is http://ift.tt/2zSIVOF and i'm trying to manage that and adding missing segment for that for example:

Route:

Route::get('{lang?}/showContent/aboutUs', array('as' => 'lang', 'uses' => 'HomeController@showAboutUsPage'))->where('lang', '.+');

mapping routes:

protected function mapWebRoutes()
{
    $locale = request()->segment(1);
    if ($locale != 'fa' && $locale != 'en') {
        $locale = 'fa';
    }
    app()->setLocale($locale);


    Route::middleware('web')
        ->namespace($this->namespace)
        ->prefix($locale)
        ->group(base_path('routes/web.php'));
}

on mapWebRoutes function i'm using multi language and manage routes, and for missing parameters as language key on segment(1) i get error, now how can i add missing segment or manage routes to redirect to correct path?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2C1V7OD
via IFTTT

Eager loader eloquent model inside of model inside of another model

I have the following querie:

  $content_movie=$this->content::with([


        'credits'=>function($query){

        $query->select('id','credit_type','department','job','characterr','person_id');
                                    },
        'collections.images'=>function($query){
            $query->select('collections_id','id','file_path');
        },

        //colecciones

        'collections'=>function($query){
        $query->select('id','name','overview');
        },

        'collections.images',

        'collections.content'=>function($query){
        $query->select('id','collections_id','name','slug');
        },

        'collections.content.images'=>function($query){
        $query->select('id','content_id','file_path','vote_count')->where('is_backdrop',0)->orderBy('vote_count','desc');
        },

        //contenido propio del elemento que estamos buscando

        'images'=>function($query){
        $query->select('content_id','is_backdrop','file_path')->orderBy('vote_count', 'desc')->first();
        },
        'genres',

        'credits.person.images',


        ])->where('slug',$args['slug'])->get(['id','name','collections_id','overview','release_date','status','video','vote_average']);


    $content=$content_movie->toJson();


To put you in situation, each 'collection' has movies and each movie has images

collections --> movies --> images.

For example:

we have the kill bill collection --> kill bill 1 --> image of kill bill 1 | kill bill 2 --> image of kill bill 2 | kill bill 3 --> image of kill bill 3

if in the above code I modify the collection.content.images.... in this way for only take 5 images of each film:

'collections.content.images'=>function($query){
        $query->select('id','content_id','file_path','vote_count')->where('is_backdrop',0)->orderBy('vote_count','desc')->limit(5);
        },

is going to take the 5 first images of kill bill 1 but not the first 5 of the 2ºpart and the 3º part.


if instead of put limit(5) I put the next code:

    'collections.content.images'=>function($query){
        $query->select('id','content_id','file_path','vote_count')->where('is_backdrop',0)->orderBy('vote_count','desc')->first();
        },

to take the first image of each film only takes the first image of kill bill 1.


how can I modify my code to get one image of each film, calling a model inside of another model, inside of another model?

I have read the documentation, but I not be able to figure out how to do this.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2DD5c54
via IFTTT

why I got this error message

ErrorException in 6e75a716e51c7050c348f50296e9bf83b3c3c282.php line 36: Undefined property: stdClass::$product_zoom_imagee (View: /var/www/vhost/arabtjk/resources/views/front/tijik/product_info.blade.php)

I edited the controller to insert one new image for the products into DB I inserted the product to test, its working, I can see the image name inside the filed that I created, Now, I should call the image as the previous developer did, I edited the product_info.blade.php from views directory and I putted the same code for the previous images but i changed the name as I putted it in the DB

Like this: this is the previous code for the existing images

product_info_image) && $product->product_info_image!='') { ?> product_info_image.''); ?>" title=""> product_name }}" alt="" src="product_info_image.''); ?>" > product_name)) }}">
                        <?php  if(file_exists(base_path().'/public/assets/admin/base/images/products/zoom/'.$product->product_zoom_image) && $product->product_zoom_image!='') { ?>
                                    <a href="<?php echo url('/assets/admin/base/images/products/zoom/'.$product->product_zoom_image.''); ?>" title=""> <img  title="" alt=""  src="<?php echo url('/assets/admin/base/images/products/zoom/'.$product->product_zoom_image.''); ?>" ></a>
                                    <?php } else{  ?>
                                    <a href="" title=""><img src="" alt=""></a>
                                    <?php } ?>

I inserted this to call the new image:

product_zoom_imagee) && $product->product_zoom_imagee!='') { ?> product_zoom_imagee.''); ?>" title=""> product_name }}" alt="" src="product_zoom_imagee.''); ?>" > product_name)) }}">

But I got that error.

Note, I am a beginner in Laravel programming, I dont know, maybe I should edit some other files

can any one guide me to solve this issue,

Many thanks for all



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CsZi7f
via IFTTT

How to get dynamic value inside loop using jquery in laravel

Always get the same id. I want to get the dynamic value in the p tag Id attribute that comes from the foreach loop every time the new id change. I want that id when I click on Read More.

<div class="carousel-inner">

    @foreach($news as $new)
      <div style="display:none" class="newsID" id=""></div>
      <div  class="item">
         <h2></h2>                          
      </div>
    @endforeach

   <p><a href="javascript:;" id="readmore-btn"  class="read-more">Read More</a></p>
</div>

Below is the jQuery code:

<script>
        $(document).on('click','.read-more',function(){

             $(this).closest('.carousel-inner').attr('id','tempID');

            var data  = $('#tempID .newsID').attr('id');

            alert(data);
            $('#tempID').removeAttr('id');
        });    

</script>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CtkOsD
via IFTTT

Display form errors (laravel validator) on bootstrap collapse

I'm using Bootstrap 3.7 and Laravel 5.5.

I have a form but it is into a bootstrap collapse. Moreover, I'm using Laravel Validator.

How it is possible to display the form (which is hide when the page is opened) when there are errors because with the Validator the page is refresh.

So I need to open the collapse to see the error. It is not very practical.

HTML:

@extends('layout.layout')

@section('content')
<div class="container">
    <h1 class="page-header">
        Administration
    </h1>

    <div class="row">
        <div class="col-lg-12">

            @if(session()->has('message'))
                <div class="alert alert-success">
                    
                </div>
            @endif

            <div class="panel-group" id="accordion">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        ...
                    </div>
                    <div id="collapseOne" class="panel-collapse collapse">
                        ...
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-heading">
                        ...
                    </div>
                    <div id="collapseTwo" class="panel-collapse collapse">
                        ...
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseAjoutEmploye">Ajout d'un employé</a>
                        </h4>
                    </div>
                    <div id="collapseAjoutEmploye" class="panel-collapse collapse">
                        <form class="form-horizontal" method="POST" action="">
                            

                            <div class="form-group ">
                                <label for="ajout-employe-email" class="col-md-4 control-label">Email </label>

                                <div class="col-md-6">
                                    <input id="ajout-employe-email" type="text" class="form-control" name="email">

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

                            <div class="form-group">
                                <div class="col-md-6 col-md-offset-4">
                                    <button type="submit" class="btn btn-primary">
                                        Enregistrer l'employé
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

PHP:

Route

Route::post('ajouterEmploye', 'AdministrationController@ajouterEmploye')->name('ajouterEmploye');

Controller:

public function ajouterEmploye(Request $request) {

    $this->validate($request,[
        'email' => 'required|email|exists:connexion'
    ] , [
        'email.required' => 'Ce champ est requis',
        'email.email'    => 'Ce champ doit être un email',
        'email.exists'   => 'Cet email est inconnu'
    ]);

    $user = User::getUserByEmail($request->email);

    User::where('id_utilisateur', '=', $user->id_utilisateur)
        ->update(['id_statut' => 1]);

    return redirect()->back()->with('message', "L'employé a bien été ajouté");
}

Thank's for help!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CpAcsn
via IFTTT

Routes in Laravel 5.4

I was using Laravel 5.2 and this how I was writing the named routes

Route::group( [ 'prefix' => 'admin' ], function () {
Route::resource( 'about', 'AboutController', [ 'as' => 'about' ] );
} );

and then this is how I call the route about.admin.about.update Now in Laravel 5.4 it's the same routes

Route::group( [ 'prefix' => 'admin' ], function () {
Route::resource( 'about', 'AboutController', [ 'as' => 'about' ] );
} );

but when I call it about.admin.about.update it gives route is not defined. another thing as I understood in named routes I can call the routes just like that about.admin.create

any clarification around this please



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zSWeyr
via IFTTT

samedi 30 décembre 2017

How to user where clause on data which is eager loaded in laravel 5 ?

I want to display only the users who are admin and according to a search term which is entered in the searchbox

I store the keyword first

$keyword = $request->get('search');

and then

$users = User::with('admin')->where('role', 'super_admin')
                    ->where(function ($query) use($keyword){
                        $query->where('id', 'LIKE', "%$keyword%")
                        ->orWhere('name', 'LIKE', "%$keyword%");
            })->paginate($perPage);

This works as im searching terms from main table that is user table

But i also want to filter it using admin table columns as

$users = User::with('admin')->where('role', 'super_admin')
                    ->where(function ($query) use($keyword){
                        $query->where('id', 'LIKE', "%$keyword%")
                        ->orWhere('email', 'LIKE', "%$keyword%")
                        ->orWhere('name', 'LIKE', "%$keyword%")
                        ->orWhere($this->admin->status, 'LIKE', "%$keyword%");
            })->paginate($perPage);

This throws an error undefined property admin

Due to this line ->orWhere($this->admin->status, 'LIKE', "%$keyword%");

So how can i use admin column in filtering data



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cg8JtV
via IFTTT

Laravel dynamic data populate in bootstrap modal

My bootstrap modal i have placed in dashboard. And the button which will populate the modal i placed in another page and in there I extends the dashboard. When i click on different product id button, product related information should comes up in modal. My question is how do i make it dynamic. means the bootstrap modal will populate based on product i clicked for quick view.

**button for quick view in index.blade.php :**

<div class="btn-quickview"> 
    <a href="#" data-toggle="modal" data-target="#modal-quickview">
        <i class="fa fa-search-plus" aria-hidden="true">
        </i> Quick View
    </a> 
</div>

  **Modal placed in dashboard.blade.php**

<div id="modal-quickview" class="modal fade" role="dialog">
    <div class="modal-dialog">
      <div class="modal-body">
        <button type="button" class="close myclose" data-dismiss="modal">×</button>
        <div class="product-view-area">         
          <div class="col-xs-12 col-sm-7 col-lg-7 col-md-7 product-details-area">
            <div class="product-name">
              <h2>Lorem Ipsum is simply</h2>
            </div>
            <div class="price-box">
              <p class="special-price"> <span class="price-label">Special Price</span> <span class="price"> $329.99 </span> </p>
              <p class="old-price"> <span class="price-label">Regular Price:</span> <span class="price"> $359.99 </span> </p>
            </div>

          </div>
        </div>
      </div>
      <div class="modal-footer"> <a href="#" class="btn-services-shop-now" data-dismiss="modal">Close</a> </div>
    </div>
  </div>
</div>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2DBHcPO
via IFTTT

MySQL 1215 Cannot add foreign key constraint - Laravel 5

I'm stuck with this infamous error and can't figure out what went wrong. I'm trying to establish relationship between two tables orders and payments, whose migrations are defined as:

class CreateOrdersTable extends Migration
{
    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->integer('customer_id')->unsigned();
            $table->integer('partner_id')->unsigned();

            $table->string('status', 20)->default(Order::getDefaultStatus());
            $table->string('paid', 20)->default('no');

            $table->decimal('visitation_charges', 20, 2)->default(0); 
            $table->decimal('taxes', 20, 2)->default(0);
            $table->decimal('charges', 20, 2)->default(0);
            $table->decimal('discount', 20, 2)->default(0);
            $table->decimal('total', 20, 2)->default(0);

            $table->foreign('customer_id')->references('id')
                  ->on('customers')->onDelete('cascade')
                  ->onUpdate('cascade');
            $table->foreign('partner_id')->references('id')
                  ->on('partners')->onDelete('cascade')
                  ->onUpdate('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('orders');
    }
}

class CreatePaymentsTable extends Migration
{
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->integer('order_id')->unsigned();
            $table->string('gateway', 100);
            $table->string('transaction_id', 100);
            $table->decimal('amount', 20, 2);
            $table->string('status', 20)->default(Payment::getDefaultStatus());
            $table->string('comments', 2000)->nullable();

            $table->foreign('order_id')->references('id')
                  ->on('orders')->onDelete('set null')
                  ->onUpdate('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('payments');
    }
}

The error I get is:

[Illuminate\Database\QueryException]                                                                   
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `payments` add constraint `payments_order_id_foreign` foreign key (`order_id`) references `orders` (`id`) on delete set null on update cascade)

I've also verified that the table engines, column types, character set, etc., are the same (following are the outputs of show create):

| orders | CREATE TABLE `orders` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `customer_id` int(10) unsigned NOT NULL,
  `partner_id` int(10) unsigned NOT NULL,
  `status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'created',
  `paid` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no',
  `visitation_charges` decimal(20,2) NOT NULL DEFAULT '0.00',
  `taxes` decimal(20,2) NOT NULL DEFAULT '0.00',
  `charges` decimal(20,2) NOT NULL DEFAULT '0.00',
  `discount` decimal(20,2) NOT NULL DEFAULT '0.00',
  `total` decimal(20,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  KEY `orders_customer_id_foreign` (`customer_id`),
  KEY `orders_partner_id_foreign` (`partner_id`),
  CONSTRAINT `orders_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `orders_partner_id_foreign` FOREIGN KEY (`partner_id`) REFERENCES `partners` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

| payments | CREATE TABLE `payments` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `order_id` int(10) unsigned NOT NULL,
  `gateway` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `transaction_id` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `amount` decimal(20,2) NOT NULL,
  `status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pending',
  `comments` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Not sure where I'm going wrong. :/



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ChFBT2
via IFTTT

Dynamic Web Twain - PHP - Adding Additional HTML Fields

I know it might be a long shot but I'm hoping someone had a similar experience at one point and might be able to point me in the right direction.

I've got a laravel project but I think I have an idea of how to incorporate the Dynamic Web Twain (http://ift.tt/2CnONEw) into it.

The only problem is I'm not quite sure how I would go about adding additional fields to the scanner UI (like what you see here: http://ift.tt/2BZiUyI).

At the moment my laravel site has a working upload portion to a model where I can submit attachments, however, with the attachment form are fields that include "visibility", "type", "upload location" etc. etc. But I can't seem to figure out how I would add fields like what I already use.

From what I've tested, this is an incredibly useful tool and would work well if I could integrate it into all aspects of my site.

The closest thing I can find is here: http://ift.tt/2ClB2Gy

Which references what is done in this demo: http://ift.tt/2BXKD2Y

As you can see, you can add a field name and field value, but I want this permanent. The other issue that I might need to work around is if I use this demo and add a value and name, this is how everything is posted and I'm not sure how to translate to something my project can understand.

-----------------------------23491353817351
Content-Disposition: form-data; name="This is a field"

Wow
-----------------------------23491353817351
Content-Disposition: form-data; name="RemoteFile"; filename="507-0.jpg"
Content-Type: application/octet-stream

ÿØÿà

If anyone can help, I'd greatly appreciate it. If you also have any other suggestions for web twain related resources, I'd gladly love to see them. This aspect is a necessary part of my project, so unfortunately there's no real way around this besides moving forward, so I'd appreciate any help I can get! :)

Thanks!! Matt



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CeyYAX
via IFTTT

Laravel 5.3 CORS with JWT auth

I have an issue with Laravel 5.3 CORS. I searched a lot on this issue, and found many recommending barryvdh for CORS. This however didn't work, and I found people mentioning that this could be caused by the use of tymondesigns jwt-auth module. Some suggests bypassing it by setting

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');

in the api.php file. This results in responses like:

Failed to load http://ift.tt/2CdcikD: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

In attempt to resolve this issue I added

header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');

to the above 2 lines. However this left me with a new issue:

PUT http://ift.tt/2CdcikD 403 (Forbidden)
Failed to load http://ift.tt/2CdcikD: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access. The response had HTTP status code 403.

Any suggestions how to go about this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BZo9yt
via IFTTT

Laravel Can't Access Model Within Event Listener

Not sure why I am having this issue, it should be a simple utilization of the use statement as is frequently done in Laravel controllers and repositories.

Is there something different for event listeners?

My error is:

Class 'App\Listeners\Asset' not found

It fires from my event listener:

<?php

namespace App\Listeners;

use App\Events\FFMPEGcreateAVideo;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\Asset;
use Auth;
use Illuminate\Support\Facades\Log;
class FFMPEGcreateAVideoListener implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  FFMPEGcreateAVideo  $event
     * @return void
     */
    public function handle(FFMPEGcreateAVideo $event)
    {
        $assetID =  $event->assetID;
        $assetURL = $event->assetURL;
        $newAssetURL = preg_replace('/(.*\.(?!.*\.))(.*)/','${1}mp4',$assetURL);
        $coverPhotoPath = $event->coverphoto;
        $asset = Asset::where("id",$assetID)->first(); //error here



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CneWTW
via IFTTT

Getting a Thread with its latest Post within the same object, latest() creates a huge overhead

Suppose I have this in my model called Thread.php:

public function post()
{
    return $this->hasMany('App\Post');
}

public function latestPost()
{
    return $this->hasOne('App\Post')->latest('id');
}

I have a page which displays all threads with their latest post. To do so, I do something like

all_threads = Thread::with('latestPost')->get();

It does this query:

select * from `posts` where `posts`.`thread_id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10') order by `id` desc

It works, but latestPost() is grabbing all posts in the table, for each thread, and then returning the latest one. This is making thousands of unnecessary objects and the overhead is already high.

The ideal would be to just take the latest Post record, but I'm not sure how to do it with Eloquent.

I've tried the following:

return $this->hasOne('App\Post')->orderBy('id', 'desc')->limit(1);
// or
return $this->hasOne('App\Post')->latest('id')->take(1);

But then only the last Thread object comes with a latestPost record. How can I optimize this query while still using Eloquent?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ltE2q5
via IFTTT

PhpStorm does not recognize associative array operator "=>"

I am learning Laravel and trying to name my routes but it seems the editor does not recognize the associative array =>, thus I can't access my URL through the short name I defined.

Problem



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BZAKlv
via IFTTT

Filter in search feature in Laravel 5.5

I would like to create a filter in a search function in Laravel 5.5, but I'm quite new and pretty much stuck at this point.

I used this tutorial: http://ift.tt/2tV463b

The search function itself works, but I am not sure how to add the filter itself. The filter should be basically be a dropdown on a blade.php which updates a variable which should change the controller I want to look in and the search criteria.

The code from my routing:

use App\Item;
use Illuminate\Support\Facades\Input;

Route::any('/', function () {
$q = Input::get ('q');
$item = Item::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'description', 'LIKE', '%' . $q . '%' )->get();
if (count($item) > 0)
    return view ('pages.index')->withDetails($item)->withQuery($q)->with('items', $item);
else
    return view ('pages.index')->withMessage ('Nothing found.')->with('items', $item);
});

Where it now says 'description' after in the query after $item, I would like 'description' to be variable and pass along the value from a dropdown that comes from a view so a user can refine their search. In theory this sounds simple as it's simple to do in PHP, but because of the MVC setup it's a bit confusing to me and it almost seems like bad practice to do this in the route?

I am wondering if this solution would be better as it seems to make more sense to do it in a controller than the route: Creating search functionality with Laravel 4

The code from that stackoverflow page:

public function search() {

$q = Input::get('myInputField');

$searchTerms = explode(' ', $q);

$query = DB::table('products');

foreach($searchTerms as $term)
{
    $query->where('name', 'LIKE', '%'. $term .'%');
}

$results = $query->get();

}

But in that case, how would I be able to add a variable into it that can be linked to a dropdown in a view? I've been looking for a way to do that, it's usually that you pass along a variable from a controller to a view and not the other way around. I could create an array in the search method and then pass that along to the view the below line, but is that the right way to do this?:

return view('pages.index')->with('items', $items);

Perhaps I'm looking at this completely the wrong way. Any help to guide me in the right direction would be appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ClR03u
via IFTTT

Laravel - How to login with first name and last name?

How can i make a login in Laravel with first name, last name and password?

I've made a register / login with php artisan make:auth. I've changed some lines of code in the user's migration, in RegisterController.php, in LoginController.php and in User.php.

The registration works. But I have a problem with the login: the username() method in LoginController.php sets the username to 'first_name'. But it should be something like 'id' or 'first_name'.'last_name', because the first_name isn't unique. How can i do that?

If two persons have the same first name, the login will fail!

(Laravel 5.5.26)

User's migration:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('password');
    $table->boolean('admin')->default(0);
    $table->boolean('active')->default(0);
    $table->string('avatar')->default('default_avatar.jpg');
    $table->unique(array('first_name', 'last_name'));
    $table->rememberToken();
    $table->timestamps();
});

LoginController:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function username()
    {
        return 'first_name';
    }

    public function login(\Illuminate\Http\Request $request) {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        // This section is the only change
        if ($this->guard()->validate($this->credentials($request))) {
            $user = $this->guard()->getLastAttempted();

            // Make sure the user is active
            if ($user->active && $this->attemptLogin($request)) {
                // Send the normal successful login response
                return $this->sendLoginResponse($request);
            } else {
                // Increment the failed login attempts and redirect back to the
                // login form with an error message.
                $this->incrementLoginAttempts($request);
                return redirect()
                    ->back()
                    ->withInput($request->only($this->username(), 'remember'))
                    ->withErrors(['active' => 'Ihr Konto ist nicht aktiviert.']);
            }
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
}

Register Controller:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'first_name'  => 'required|string|max:20|unique_with:users,last_name',
            'last_name' => 'required|string|max:20',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'password' => bcrypt($data['password']),
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
        ]);
    }

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();
        event(new Registered($user = $this->create($request->all())));
        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }
}

User.php:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'password', 'first_name', 'last_name',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function goals(){
        return $this->hasMany('App\Goal');
    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CcS5ex
via IFTTT

Foreign key constraint is incorrectly formed error Laravel 5.5

I am getting an error when running the migration command.

This is the admin table schema

Schema::create('admin', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('user_id')->unique();

                $table->timestamps();

                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            });

And the other is the user table that comes with laravel installation.

I want to create a foreign key for user_id but it gives error



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2DyUuws
via IFTTT

The compiled services file has been removed in laravel5.4

While installing the package through composer in laravel5.4 i am getting the issue "The compiled services file has been removed".



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lmOoZz
via IFTTT

Call to undefined method Illuminate\Database\Query\Builder::method() error in laravel 5

I am getting an error when i click the delete button which calls Controller@delete method on a controller.

Call to undefined method Illuminate\Database\Query\Builder::destroy()

throw new BadMethodCallException("Call to undefined method {$className}::{$method}()");

destroy method

    public function destroy($id)
    {
        User::destroy($id);
        return redirect('/home')->with('message', 'Deleted!');
    }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2pWUqop
via IFTTT

Laravel 5.5 and Angular 4 set cookie

I used laravel as backend (that implemented at homestead - mydomain.test) and angular 4 as frontend (that implemented at http://localhost:4200), now, I want to set a cookie from backend to frontend browser.
backend controller: return response(['access_token'=>$response['access_token'], 'expires_in' => $response['expires_in']]) ->withCookie($cookie); and response is: Access-Control-Allow-Origin:* Cache-Control:no-cache, private Connection:keep-alive Content-Type:application/json Date:Sat, 30 Dec 2017 09:01:11 GMT Server:nginx/1.11.9 Set-Cookie:refreshToken=def50200b16fb4563dfa726245a813985f300394fcce058b32138d85d62791e53869049c4dc71358e5789fb267457313e295f43b4f8dc8a5c4a22b03577ef77fb114f71fe17dbad637fc07105cbc67f58adbc905008fb870eae6b238047c9037fdbcf2710909538b36f8432f9528d52c9afd8774fe68ebfb11d125f0951b69ede08e164a1b0f1fe1510906a30858cb1946868a7d89d2d289b27140155b4fca33bee35ce9560696e023a484412bbbf26751ca81d96c88879c6a885b0ed72cc0b0c63639df38b3f7170561c559570cd5fa8faeec89ce06ddaf073a4634dcd5d49c0c5500dc63aeec5d5ffa99c2bad4c817f454c3bfa228397f18162e6fce64790da2f138a506bc906ae944a9aee29f1aa2b49bf2189d703706b2f475588f819985ad6942312070f5c887eec3deaa0761157f3cd86f0a016f3b19a311223c9b703a89efdfd96a878330b4e7dc86b0759c91be9bd7905ed6b94fec3587528402b7; expires=Thu, 22-Aug-2019 09:01:11 GMT; Max-Age=51840000; path=/; HttpOnly Transfer-Encoding:chunked Vary:Origin X-RateLimit-Limit:60 X-RateLimit-Remaining:59

but when I want to send the cookie from frontend to backend , it does not work! I used angular 4:

``` refreshToken(){

const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + this.getToken()})
let options = new RequestOptions({ headers: headers, withCredentials: true });

return this.http.post(API_DOMAIN + 'refresh', JSON.stringify({}), options)
  .map(
    (response) => {
      console.log(response.json());
      return response.json()
    },
  )

} ```

and backend side:

$refreshToken = $request->cookie(self::REFRESH_TOKEN); var_dump($refreshToken); // to be null always

can you help me to solve these problems?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BVrqPk
via IFTTT

Laravel Yajra Datatable plugin 404 error in console

I am trying to use Laravel's Yajra Plugin for datatables i tryed with single modle (user model) it working fine but when i tryed eloquent relationships i get 404 erorrs here is my code.

Table View

@extends('layouts.app')

@section('content')

<table class="table table-bordered" id="users-table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Username</th>
            <th>User Role</th>
            <th>Phone</th> /* Where i remove this column datatable works file */
        </tr>
    </thead>
</table>

<script>

    $(function() {
        $('#users-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{!! route('user_datatable_data') !!}',
            columns: [
                { data: 'id', name: 'id' },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' },
                { data: 'username', name: 'username' },
                { data: 'role.role_name', name: 'role.role_name' },
                { data: 'phone', name: 'phone' } // Where i remove this column datatable works file
            ]
        });
    });
</script>

Here is my controller handling view and datatables

function index()
{
    $data['page_title'] = 'Users';
    $data['panel_title'] = 'User list';
    $data['panel_description'] = 'Add, Edit Delete and deactivate users';
    $data['users'] =  User::all();
    return view('settings.users.user_list', $data);
}

function datatable(){
    return Datatables::of(User::query()->with('role')->get())->make(true);
}

Here is my routes

Route::get('users', 'UserController@index')->name('user_list');
Route::get('datatable', 'UserController@datatable')->name('user_datatable_data');



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cq1sVe
via IFTTT

I can not configure the laravel + broadcasting + socket.io + redis with passport

public channels function normally. For private channels, the error is:

⚠ [04:53:17] - 4JvRYXBHYYCJCB1UAAAD could not be authenticated to private-notification.1 {"message":"Unauthenticated."} Client can not be authenticated, got HTTP status 401

I tried every possible possibility and I did not succeed!I'm desperate because I have time to deliver this functionality. Can someone help me? Why can not I authenticate private channels with passport?

My current setting:

BroadcastServiceProvider.php

ublic function boot()
{

    Broadcast::routes(['middleware' => 'auth:api']);
    require base_path('routes/channels.php');
}

laravel-echo-server.json

{
    "authHost": "http://ift.tt/2Clnvih",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "9c93c4f229bb615f",
            "key": "6efe137de4101bc1b0429e6afd29e817"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "http://ift.tt/2Clnvih",
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": ""
}

channels.php

Broadcast::channel('notification.1', function ($user, $lojaId) {
    return true;
});

SendNotification.php

public function broadcastOn()
{
        //return new Channel('notification');
        return new PrivateChannel('notification.1');
}

my frontend (file vue)

Vue.use(VueEcho, {
    broadcaster: 'socket.io',
    host: 'localhost:6001',
    auth: {
        headers: {
            Authorization: 'Bearer' + sessionStorage.getItem("ss348978Token")
        },
    },
});

.....

this.$echo.private('notification.1').listen('SendNotification', (payload) => {
            this.mensagem.push(payload.data)

});



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cn81dG
via IFTTT

vendredi 29 décembre 2017

When I install Laravel/Passport auth is not working i always get page expired error

I have installed Auth using Make::Auth method. and it worked fine. but when i installed passport i get error saying page expired when trying to login. and login doest not seems to works as expected.

any help may be appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cc3YBC
via IFTTT

how to redirect user according to role in laravel 5.4

I am using laratrust package. i have multiple user roles i want to redirect user according to their role but i am not able to redirect user according their role.

route.php

// If User Role Master Administration Call this Route
Route::group(['prefix' => 'dashboard', 'middleware' => ['role:master-admin']], function(){

    Route::get('/', 'HomeController@index')->name('home');
    Route::resource('/branches','BranchController');
});



// If User Role Company Admin Call this Route
Route::group(['prefix' => 'dashboard', 'middleware' => ['role:company-admin']], function(){
    Route::resource('/','CompanyController');
});

// If User Role guest user Call this Route
Route::group(['prefix' => 'dashboard', 'middleware' => ['role:guest-user']], function(){
    Route::resource('/','CompanyController');
});



Route::get('/error','error\ErrorController@pageNotFound');



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BUOIFc
via IFTTT

laravel 5.5 controller name should be plural or singular ?

what is the naming convention in laravel 5.5 for controllers . they should be singular or plural . I saw some people use singular and some people use plural for that . what is the correct form ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cmu7Nu
via IFTTT

Laravel Validation - how to return the same category and subcategory that had been selected?

Good evening, I'm developing a form that contains categories and subcategories, the subcategories only appear after the category has been selected. So far so good, when the form is submitted and contains some validation error handled by the validation method, the system returns to the form screen with all the fields except the sub category field that is requested when the category is chosen. ..

How do I do when an error occurs and return to the form screen come with the same subcategory options that had been selected?

Note: I have a provider that sends the categories to the view, but I do not know how to retrieve the category_id to send the subcategories, nor do I know if this would be the best way ...



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lswIL2
via IFTTT

Verifying if request from inside website

I am trying apply some protection for videos played inside website from being downloaded by other than the player itself.

I figured out the following solution to do

In view file :

@php
$token = uniqid ();
Session::put('videoToken',$token);
@endphp

<video id="my-video" class="video-js" controls preload="auto" width="800" height="450"
                           poster="" data-setup="{}">
                        <source src="?token=$token" type='video/mp4'>

                        <p class="vjs-no-js">
                            To view this video please enable JavaScript, and consider upgrading to a web browser that
                            <a href="http://ift.tt/1n3ZgSJ" target="_blank">supports HTML5 video</a>
                        </p>
                    </video>

videoView Route:-

Route::get('/video/{id}',function(Request $request){
if ($request->token == Session::get('videoToken'))
{
$post = Post::find($id);
return response()->download($post->path, 'vid.mp4');
}
else{
die();
}
})->name('videoView');

Well, for the above coding , i will make sure that the video file is only generated if $token verified , how can i add extra layer to verify if request is coming from the page where player is, so any one if try to access that video by using the URL : http://ift.tt/2zNqryE , it wont work.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2C9HrFv
via IFTTT

Trying to get property of non-object when using One to Many relationship in Laravel

So I keep getting this error when trying to get the name of the user who created a post.

My models look like this:

class User extends Authenticatable {
    use Notifiable, CanResetPassword;

    public function posts() {
        return $this->hasMany('App\Post');
    }
}

&

class Post extends Model {

    public function user() {
        return $this->belongsTo('App\User', 'user_id');
    }
}

I try to display the name by doing this in my view:

@foreach($posts as $post)
    <tr>
        <td></td>          
    </tr>
@endforeach

And my controller looks like this:

public function getAdminIndex() {
    $posts = Post::orderBy('id', 'desc')->get();
    $comments = Comment::all();
    $likes = Like::all();
    $users = User::all();

    return view('admin.index', ['posts' => $posts, 'comments' => $comments, 'likes' => $likes, 'users' => $users]);
}

Can anyone please tell me what I'm doing wrong?

Thank you very much!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CoG4Qg
via IFTTT

Laravel merge multiple collections and sort by corresponding datetime field

I have multiple collections merging into one, then sorting that one by datetime to ultimately create a timeline between the collections.

Heres the catch, the datetime columns to sort are different names.

Is there anything I can do to make this cleaner - possibly attach the foreach loop with the ->merge? Looks ugly with the foreach loop. note: code below works but I feel it's a lazy way out and might be slow with more items in the collection.

// Create timeline, sortby creation datetimes.
$TimelineItems = collect();
$AppointmentTemps = collect($Appointments);
$SalesResultTemps = $lead->SalesResult;

$TimelineItems = $AppointmentTemps->merge($SalesResultTemps);
foreach ($TimelineItems as $key => $TimelineItem) {
    if(!empty($TimelineItem->appointment_created)) {
        $TimelineItems[$key]->created_at = $TimelineItem->appointment_created;
    }
    if(!empty($TimelineItem->salesresult_created_timestamp)) {
        $TimelineItems[$key]->created_at = $TimelineItem->salesresult_created_timestamp;
    }
}
$TimelineItems = $TimelineItems->sortByDesc('created_at');
dd($TimelineItems);



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CnZsgg
via IFTTT

Update laravel with eloque ORM

I update my blog whith eloque ORM and the code don't start

public function save_edit(Request $request, $id){
      DB::table('produit')
        ->where('po_id', $id)
        ->update(['po_prix' => 85]);
}

Where is the problem? thank you



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Duq0f9
via IFTTT

Laravel get only models with current version

I have implemented custom model versioning in Laravel Framework. There is couple of columns handling it in the database table: sibling_id (links model's different versions together), version, accepted and validFrom.

For example:

| id | sibling_id | version | accepted | validFrom  | ... |
|----|------------|---------|----------|------------|-----|
| 1  | 1          | 1       | 1        | 2017-12-01 |     |
| 2  | 1          | 2       | 1        | 2018-06-01 |     |
| 3  | 2          | 1       | 1        | 2017-12-10 |     |
| 4  | 2          | 2       | 0        | 2017-12-28 |     |
| 5  | 3          | 1       | 0        | 2017-12-01 |     |

What I mean with current model:

  • model having the biggest version number within accepted and valid modals
  • OR version 1 if there isn't any other versions

I would like to have some way to get normally only current model grouped by sibling_id (so within this example the collection should include models 1, 3 and 5). This should work like same way than Laravel's withTrashed() function so that I can include all if I want to (for example version history).

Maybe this can be done somehow with the scopes but I felt it complicated because of the "sibling grouping" and another complex filters so I ended up to ask here.

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lr6E2Z
via IFTTT

LARAVEL - cannot access my public folder via URL

I am trying to show image in my blade view.

I tried:

 <img src=>

Also:

<img src= /images/1514562220.jpg')>

If i type http://localhost:8000/public/images/1514562220.jpg in browser 404 page appear.

If i type http://localhost:8000/images/1514562220.jpg in browser i get ERR_INVALID_HTTP_RESPONSE.

When i inspect element in browser i see following adress:

http://localhost:8000/public/images/1514562220.jpg

but img is not showing

I dont know if it has something to do with it but there is some kind of block on icon.

enter image description here

My 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]



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2liCmQU
via IFTTT

Modificar un contacto en CRM vtiger mediante Webservices

Estoy tratando de modificar un contacto del CRM vtiger no he podido encontrar la solución creo que la forma en la que estoy realizando la modifcación es la correcta pero cuando realizo el proceso no pasa nada con el contacto los datos siguen igual.Espero y alguien ya aya podido arreglar este error Les agradezco por adelantado

           $reponse = $client->request('GET', VT_URL, [
                 'query' => [
                     'sessionName' => $sessionId,
                     'operation' => 'retrieve',
                     'id' => $idvtiger
                 ]
             ]);
            $jsonResponse = json_decode($reponse->getBody()->getContents());
            $retrievedObject = $jsonResponse->result;

            $retrievedObject = array(   
            'firstname'=> $request->nombre,
            'lastname'=> $request->apellidos,
            'email'=> $request->correo,
            'cf_765'=> $request->pasw
            );  
            $objectJson = json_encode($retrievedObject);

            $updatecontact = $client->request('POST', VT_URL, [
                'form_params' => [
                    'sessionName' => $sessionId,
                    'operation' => 'update', 
                    'element' => $objectJson
                    ]
            ]);



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Egk5vu
via IFTTT

How can I insert two models at once with one model with multiple rows insert uisng Laravel 5.4

I have two migration tables Patrol(A) and Patrol_Details(B), I would like to insert to Patrol and same time to Patrol_details,Patrol, A hasMany B and B belongsTo A, in B would like to add multiple rows at once and also insert A_Id Here is My Controller, When I Try to insert, Insert only Table A

public function store(Request $request)
{
$this->validate($request, [
'unit_leader' => 'required',
'leader_no' => 'required',
'patrol_identity' => 'required',
'date' => 'required',       
]);
$patrols = new Patrol;
$patrols->unit_leader = $request->unit_leader;
$patrols->leader_no = $request->leader_no;
$patrols->patrol_identity = $request->patrol_identity;
$patrols->date = Carbon::parse($patrols->date)->format('Y/m/d');
$patrols->intels_id = $request->intels_id;
$patrols->save();


}
$rows = $request->input('rows');
foreach ($rows as $row)
{
$details[] = [
'full_name' => $row['full_name'],
'organisation' => $row['organisation'],
'position_grade' => $row['position_grade'],
            ];
}

 $patrols->patrol->Patrol_Detail()->save($patrol->Patrol_Detail);

$patrols->Patrol_Detail()->save($rows);
return redirect()->route('patrol.index')->with('success' , ' created successfully');

}

A MODEL

class Patrol extends Model
{
    public function intel()
    {
        return $this->belongsTo('App\Model\im\Intel');
    }

    public function patrol_detail()
    {
        return $this->hasMany('App\Model\im\Patrol_Detail','patrol_id','id');
    }
}

B MODEL

class Patrol_Detail extends Model
{

    protected $fillable = ['full_name', 'organisation','position_grade'];

    public function patrol()
    {
        return $this->belongsTo('App\Model\im\patrol');
    }
}

When I Try to insert, Insert only Table A, any guidance will be appreciated Thank you



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ClICkJ
via IFTTT

trying to get property of non-object multi-auth

I use Hesto/multi-auth package. The username when I login success default redirect in customer.layout.auth, how can I to redirect in my blade, Example: welcome.blade.php, I can't use in another blade, it error Trying to get property of non-object . How to fix it, please help me !

AppServiceProvider.php

       public function register()
        {
            //
                if ($this->app->environment() == 'local') {
                 $this->app->register('Hesto\MultiAuth\MultiAuthServiceProvider');
                }
        }

auth.blade.php



 @if (Auth::guest())
                            <li><a href="">Login</a></li>
                            <li><a href="">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                     <span class="caret"></span>
                                </a>

                                <ul class="dropdown-menu" role="menu">
                                    <li>
                                        <a href=""
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                            Logout
                                        </a>

                                        <form id="logout-form" action="" method="POST" style="display: none;">
                                            
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endif



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2EclDX8
via IFTTT

Laravel: method to set the value of a custom primary key

My Document model has a custom primary key name, so I typed:

class Document extends Model {

    protected $primaryKey = 'fluxo_mensagem_id';

After this, I suppose Laravel to know my primary key name and then I wouldn't expected to have to type it manually every time I need to set its value. Something like:

$document = new Document;
$document->setPrimary($pivot->id);

Instead of:

$document = new Document;
$document->fluxo_mensagem_id = $pivot->id;

For more details, my partial ER diagram:

enter image description here

Question 1

Laravel provides some method to set primary key values dynamically after custom names defined on model class?

Question 2

On document table, the column fluxo_mensagem_id is a foreign key that references id fluxo_mensagem pivot (intermediate) table. There's some way to "associate" (as we can do with Belongs To relationships) Pivot object to a Document model?

For example:

  $pivot = $mensagem->fluxos()->first()->pivot;
  $document = new Document;
  $document->fluxoMensagem()->associate($pivot); 

This would fit the problem because his intention is to set the foreign key on the child model.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lp0T67
via IFTTT

Laravel Modal Factories with Tests

I'm trying to create a team and then add that team to a game and then add that game to the event, however, when the game is created it auto generates an event to attach to the event. In normal circumstances this is fine but because I'm testing the team's joined at compared to the event their first game is on then I need to create an event with a specific date. I can't create the event first because the game has to be created first to be able to add it to it.

Does anyone have a suggestion on correcting my logic so that I can get a game and event created correctly?

/** @test */
public function a_team_with_a_game_after_they_started_the_season_cannot_have_their_joined_at_date_after_their_first_match()
{
    $team = factory(Team::class)->create(['joined_at' => '2017-10-08']);

    $game = GameFactory::create([], [$team]);
    $event = EventFactory::create(['date' => '2017-10-09'], null, $game);

    $validator = new BeforeFirstGameDate($wrestler);

    $this->assertFalse($validator->passes('joined_at', '2017-10-10'));
    $this->assertEquals('The joined at date cannot be AFTER the team\'s first game.', $validator->message());
}

Factories

<?php

use App\Models\Game;
use App\Models\Team;

class GameFactory
{
    public static function create($overrides = [], $teams = [])
    {
        $match = factory(Game::class)->create($overrides);

        self::addTeamsForGame($teams, $game);

        return $game;
    }

     /**
     * @param $teams
     * @param $game
     */
    public static function addTeamsForGame($teams, $game)
    {
        $teamsForGame = [];

        $numberOfTeamsToAdd = $numberOfTeams - count($teams);

        if ($numberOfTeamsToAdd) {
            $teamsForMatch = factory(Team::class, $numberOfTeamsToAdd)->create();
            array_push($teams, $teamsForGame);
        } else {
            array_push($teams, $teamsForGame);
        }

        $match->addTeams($teamsForGame);
    }
}


<?php

use App\Models\Event;

class EventFactory
{
    public static function create($overrides = [], $totalNumberOfGames = 8, $games = [])
    {
        $event = factory(Event::class)->create($overrides);

        $numberOfGamesToAdd = $totalNumberOfGames - count($games);
        $gameToStartAt = count($games) + 1;

        foreach (array_wrap($games) as $game) {
            $game->addToEvent($event);
        }

        for ($gameNumber = $gameToStartAt; $gameNumber <= $numberOfGamesToAdd; $gameNumber++) {
            GameFactory::create(['event_id' => $event->id, 'game_number' => $gameNumber]);
        }

        return $event;
    }
}


$factory->define(App\Models\Game::class, function (Faker\Generator $faker) {
    static $order = 1;
    return [
        'event_id' => function () {
            return factory(App\Models\Event::class)->create()->id;
        },
        'game_number' => $order++,

    ];  
});

$factory->define(App\Models\Event::class, function (Faker\Generator $faker) {
    $name = $faker->sentence;
    return [
        'name' => $name,
        'slug' => str_slug($name),
        'date' => $faker->dateTimeBetween('-10 years'),
    ];
 });



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2liqX3n
via IFTTT

Is it possible to run dusk on dev/staging/prod server?

On the local machine, I am able to setup the dusk and run the test cases. On Dev server, I am facing following issue.

Failed to connect to localhost port 9515: Connection refused Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"desiredCapabilities":{"browserName":"chrome","platform":"ANY"}}

Can anyone helps me to solve this issue? Or how to run dusk automation on dev server?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2C7R3QZ
via IFTTT

Laravel raw query that counts results per month and aggregates

I have the following query

$this->builder = (DB::table('sales')
        ->select(DB::raw('DATE_FORMAT(sale_date, "%M") as sale_date'), DB::raw('count(*) as sales'))
        ->where('sale_date', '>', $lookback->toDateTimeString())
        ->orderBy('sale_date', 'asc')
        ->groupBy('sale_date'));

Despite specifying the month %M to group the results, it's just counting each date and giving the label as the month, so something like this:

sale_date , sales
 August   ,  1
 August   ,  3
 August   ,  2

Instead of what I expect:

sale_date , sales
 August   ,  6

What am I doing wrong here, I do have the option of just summing those within the javascript once I get the results from the API, however I don't think it should be necessary right?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zMdXY6
via IFTTT

Laravel passport custom error message and status code when user unauthorized

my project is running on Laravel 5.4 and I use passport to make authentication via api with bearer token. everything works fine, but when unauthorized user tries to reach resource that require authentication, the user gets error message 405 method not allowed enter image description here

but I want response to be 401 unauthorized . how can change this, and send only response with message, instead of exception? I did research, but couldn't find anything. I use standard laravel middleware for authorization auth:api. my routes grouped in middleware

Route::group(['middleware' => 'auth:api'], function () {
  // these routes should return 401 if user not authenticated
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Ci6a9R
via IFTTT

Laravel Auth routing redirects back

I've created a project and programmed most the content locally until I've got a server. Now I have a server and I moved the files to the server. After I've got the project run normally, I've got in trouble with the authentification. ( I addet the authentification on the server, it wasn't there locally ).

Everytime I try to login or to register I only get redirected to the login/register route without any error or something like that. The DB connection works fine, I've tried getting some data of it and that worked.

I looked for the auth routes and tried to return the http header data in the register function but the programm doesn't reach this function at all.

I also tried to overwrite the register post Route in Router.php in /vendor/framework/src/Illuminate/Routing/Router.php from:

        $this->post('register', 'Auth\RegisterController@register');

to

        $this->post('register', 'TestController@test');

Just to look if in the @test function in my TestController will be reachted, but nothing. Got redirected again.

However, I haven't changed the auth controller etc. at all beside the redirect route in the login/register-controller

Here are my routes in my web.php:

Route::group(['middleware' => 'auth', 'web'], function () {
    // my routes - the user shall only see them if they are logged in
)};

Auth::routes();

If I log a user manually in, everything works fine

I really have no clue what to do anymore, does someone have a clue?


php artisan route:list :

enter image description here



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BPMzdF
via IFTTT

JWT-Auth responds token_not_provided when i try to validate the token

As far as i know everything is proper in back end that is Laravel, because its working well in Postman, but when i try to validate token from front-end (Angular 4) JWT-Auth throws error {"error":"token_not_provided"} This is how my request header looks like.

POST /api/user HTTP/1.1
Accept:          application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-IN,en-GB;q=0.9,en-US;q=0.8,en;q=0.7
Connection:      keep-alive
Content-Length:  439
Content-Type:    application/json
Host:            localhost:8000
Origin:          http://localhost:4200
Referer:         http://localhost:4200/
User-Agent:      Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36

{
    "header": {
        "Content-type": "application/json",
        "Authorization": "Bearer eyJ0eXAiOiJKV .... vBMbwBypj6uv4Ks",
        "Accept": "application/json;odata=verbose"
    }
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BPDAJt
via IFTTT

ErrorException Object of class Laravel\Socialite\Two\User could not be converted to string

I am trying to implement socialite in laravel

When the redirect happens from google and $user = Socialite::driver('google')->stateless()->user(); instruction is called i get this error

ErrorException Object of class Laravel\Socialite\Two\User could not be converted to string

any help appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2C8qdbB
via IFTTT

Is there any needs to install anything to run another page(except index.php) in laravel framework. Except npm, model, controller

i've tried a project and can't connect another page in laravel. there is an error of (Sorry, the page you are looking for could not be found.)



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zN50hy
via IFTTT

Laravel 5 - "Trying to get property of non-object"

Below I got my middleware that updates IP of the user.

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\Guard;

class UserMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function __construct(Guard $auth)
    {
         $this->auth = $auth;
    }
    public function handle($request, Closure $next)
    {
        User::where('id', $this->auth->user()->id)->update(['last_visit_ip' => '231']);
        return $next($request);
    }
}

Some notification is popping me up "Trying to get property of non-object" Any idea how to fix it?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2C6sMee
via IFTTT

Azure storage - queues - Guzzle Timeouts

I'm using the Azure Storage service as a queue for my PHP multi-tenant app; i'm currently migrating customers over and are now after +150 facing some issues. Each customer has their own "queue".

Every second or third call to the queue service is returning Guzzle Timeouts; this is not sustainable, especially not since i still need +200 clients- and more are coming.

The error recieved is:

cURL error 7: Failed to connect to customerqueue.queue.core.windows.net port 443: Connection timed out (see http://ift.tt/1mgwZgQ) 

Has anyone had this issue before? And knows that the fix is or how to fix it?

Thanks, Jonas



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2liO1is
via IFTTT

Strange behaviour in laravel routing

Consider the two following laravel routing directives:

    Route::get('/a/b', function(){return "One";});
     .
     .
     .
    Route::get('/a/b', function(){return "Two";});

I know they don't make much sense, but consider them. Theoretically, the priority is that the first one would prevail over the second. But if you access the site with

http://whatever.com/a/b

the response is

Two

I guess this happens because even if the real selected directive is the first, it happened that the second one OVERWROTE the first one with his return value.

My question is: Is this the intended behaviour? Because it may be obvious when you only have two lines in your routes file, but not when you have dozens of them, and you inadvertly could duplicate the same directive and think that the return value of the first one is the one to be returned.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2C94sbS
via IFTTT

Best way to create relational database model for different Customer modals in Laravel

In my Laravel project there are Vehicle Owner, Driver and Customer models. There is default laravel user table also for auth. Each of them is separate tables in database. Now I'm adding credits and debts for all of them. It's working but I'm not happy with solution because:

  1. There are several common fields repeating in each.
  2. When user will add credit/invoice I'm joining 3 tables.
  3. Financial table seems more complex

Finance

  userType       | userID       | amouth       
  ------         |  ------      |----------- 
  VehicleOwner   |  5           | -500
  Driver         |  5           |  200
  Customer       |  5           |  200

Maybe one solution could be relate all 3 tables with one human table:

Human All Basic User Info will be related every human being. Extend it:

1.Driver (extend driving license info)
2.Customer (extend corporate info)
3.Vehicle Owner (extend driver info)

I'm new in Laravel and looking for best practice?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Ecggaw
via IFTTT

How to insert a value to created_at field using Query Builder

I am new to Laravel. I am looking for a way to insert a value to specific field such as created_at automatically whenever the row is inserted to the DB table.

I found out that only Eloquent way which uses some Model->save() inserts timestamp to desired field.

But I want to be able to insert a value even when I use QueryBuilder. Is there any way to do so?

I have looked at this post: Query builder not inserting timestamps

Any advice would be appreciated.

Thank you in advance



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cn2wJi
via IFTTT

laravel - Updating relation with many 'childs'

I have this database:
parents

| id |  name  |  
+----+--------+  
|  1 |  Paul  |  
|  2 |  Annet |

childs

| id |    name   |  
+----+-----------+  
|  1 |  Micheal  |  
|  2 |   Susan   |

and pivot table parents_childs

| parent_id | child_id | custom_field_1 | custom_field_2 |  
+-----------+----------+----------------+----------------+  
|     1     |     1    |    value_1     |      (null)    |  
|     2     |     1    |  value_another |     value_3    |

and standard relation belongsToMany

public function parents(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
    return $this->belongsToMany('\App\Parent', 'parents_childs', 'child_id', 'parent_id')
                ->withPivot(
                    'custom_field_1',
                    'custom_field_2'
                );
}

Now I need to update pivot fields of specified child but only for one parent, eg.

SET red_value FOR custom_field_2 WHERE child_id = 1 AND parent_id = 2

How can I do this without QueryBuilder?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2pWo0um
via IFTTT

Laravel response json not working on live server, it gives connection timeout

I have deployed my project to AWS server with php7.1 mysql, and I am using laravel 5.5. All things are working fine except ajax call response. When I try to request through ajax call ($.post method) It show pending status for a while, but gives connection time out with status failed. Ajax call works fine on my local setup. Can anyone help me to short it out. Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Ee24xx
via IFTTT

jeudi 28 décembre 2017

How to use Multiple Guard in Laravel 5.5 using Tymon\JWT

I have five guards options in api config file like below.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'user_client',
    ],

    'api_admin' => [
        'driver' => 'jwt',
        'provider' => 'user_admin',
    ],
    'api_client' => [
        'driver' => 'jwt',
        'provider' => 'user_client',
    ],
    'user_carrier' => [
        'driver' => 'jwt',
        'provider' => 'user_carrier',
    ],
    'user_client' => [
        'driver' => 'jwt',
        'provider' => 'user_client',
    ]
],

So I intend to use different "guard" for different types of requests like below.

$guard = request()->get('guard'); // driver or admin
JWTAuth::guard('api_'.$guard)

This gives me this error:

"Method [guard] does not exist."

But when I use default Auth class supported by Laravel, it works fine.

Here is my working code :

$guard = request()->get('guard'); // driver or admin
Auth::guard('api_'.$guard)

How can I solve this problem ?

Any suggestion or advice would be appreciated.

Thank you in advance



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cj1Wi8
via IFTTT

Show the name of the other table by pivot table

The tables:

users

-id

-name

users_companies

-id

-user_id

-company_id

companies

-id

-name

users_companies is the pivot table

I want to show or get the "name" field of a table, this is my code in the table

<td></td>

but then it shows like this in the column of the table. I just want to get the value of the name like "VCY BT Holdings". Thanks

[{"id":5,"name":"VCY BT Holdings","deleted_at":null,"created_at":"2017-12-23 02:24:50","updated_at":"2017-12-23 02:24:50","pivot":{"user_id":14,"company_id":5}}] [enter image description here]1



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Cjz75p
via IFTTT

Making CRUD for a resource with one-to-one relationships on Backback for Laravel

Imagine a User-model that is associated with one Phone-model as a one-to-one relationship as defined by Eloquent Relationships, meaning that the User-model has a function:

/**
 * Get the phone record associated with the user.
 */
public function phone()
{
    return $this->hasOne('App\Phone');
}

while the Phone-model has a function:

/**
 * Get the user that owns the phone.
 */
public function user()
{
    return $this->belongsTo('App\User');
}

The question is now how to make a CRUD controller in Backpack for Laravel, which makes is possible to add a new User where the Phone is also provided in the same CRUD add/edit form.

It seems to be standard that you add a Phone resource and then add a User resource where there is a select-field where you can choose an existing Phone resources, but instead I am trying to add a new User with a new Phone in one CRUD controller, and also editing a User while at the same time editing his Phone.

Here are two examples of how it could look: Illustration of Backpack Add-form for a User-model with a one-to-one relation to the Phone-model

I hope this makes sense.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2E7Z6uw
via IFTTT

Laravel Impossible to Create Root Directory

I've checked out the other posts about this, mine seems to be unique for some reason

Essentially what I'm trying to do is store uploaded photos in the public directory for easy access, however when I store them I'm trying to store them in a user specific folder, so

/public/photos/$User->id/$filename.jpg

Right now I have Dropzone uploading the file, and I've added to my filesystem.php this statement

'public_uploads' => [
  'driver' => 'local',
  'root'   => public_path(),
],

So in theory when I access that using

Storage::disk('public_uploads') 

it should retrieve the correct path

Here's my controller as well

$User = User::find(Auth::user()->id);
$Photo = Request::file('photo');
Storage::disk('public_uploads')->put("photos/$User->id", $Photo);

Then I get this error from Laravel on upload

{message: "Impossible to create the root directory "/censoredfilesystem/public/Photos/1".",…}

No idea where the period is coming from and any help is greatly appreciated

Thanks all!

  • Zach


from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2pQcUXv
via IFTTT

Laravel: Issue in vaildation

I am facing some issue in validation. below is my code

I have two fields in database

user & Address

in user.blade i have input field

<input type="text" name"username"/>

 @if(errors->has('user'))

@endif

in controller i have method:

public function store(Request $request)
{
   $this->validate(request(),[

   'user'=>'required'

]);
}

If i use above code, the validation is not working, but when i change the input field name 'username' to 'user' its start working. is that compulsory to use the same input field name which is in db ???? or any other way to fix this problem ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lnbH4o
via IFTTT

laravel get Illegal string offset error on getting jsonObject value

in this result of

{#457 ▼
  +"id": 14
  +"amount": "110092"
  +"discount": 0
  +"images": "{"images":{"original":"\/uploads\/post_images\/2017\/1513070310.jpeg","300":"\/uploads\/post_images\/2017\/300_1513070310.jpeg","600":"\/uploads\/post_images\/2017\/600_1513070310.jpeg","900":"\/uploads\/post_images\/2017\/900_1513070310.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1513070310.jpeg"} ◀"
  +"created_at": "2017-12-28 17:48:48"
  +"updated_at": "2017-12-28 19:24:18"
}

query, i'm trying to get thumbnail from images column which images is JsonObject, but i get this error:

"Illegal string offset 'thumbnail'"

my code:

$userShoppings = \DB::table('payments as s')
    ->join('products as p', 's.product_id', '=', 'p.id')
    ->select('p.*', 's.*',\DB::raw('s.ordering_count * s.price as cost'))
    ->whereUserId(auth()->user()->id)
    ->first();

dd($userShoppings->images['thumbnail']);

or

dd($userShoppings->images['images']['thumbnail']);

error:

"Illegal string offset 'images'"

my models:

class Shopping extends Model
{
    protected $fillable = [];

    protected $casts=[
        'images'=>'array'
    ];
}

class Payment extends Model
{
    protected $fillable = [];

    protected $casts=[
        'images'=>'array'
    ];
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lmT2pr
via IFTTT

Why does a Capitalization error work locally...?

I've encountered this situation a couple of times now where everything is working fine locally, then when I push to remote server, I get errors due to simple Capitalization error.

'App\Useraction' vs 'App\UserAction

The same error exists locally, so why does everything still work?

Is there an Apache or PHP setting that's allowing this to work?

I'd like to change my local environment so I can catch these..!

Using: Apache 2.4.25 / PHP 7.1 / Laravel 5.4



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BOW5xG
via IFTTT

Uncaught ReferenceError: Echo is not defined

I almost dont have any ideas about javascript. I watched some videos to make real time chat for my project and i get these errors.

Notes : Before this real time chat was working nice, just something easy happened and not its not working and i really dont know why its happening. I need your help, thank you in advance!..

app.js:59006 Uncaught ReferenceError: Echo is not defined
    at Object.<anonymous> (app.js:59006)
    at __webpack_require__ (app.js:20)
    at Object.VERSION (app.js:28107)
    at __webpack_require__ (app.js:20)
    at Object.defineProperty.value (app.js:28043)
    at __webpack_require__ (app.js:20)
    at Object.<anonymous> (app.js:28028)
    at __webpack_require__ (app.js:20)
    at app.js:63
    at app.js:66

When I press this error shows this :

Echo.join('chat').here(function (users) { X

    __WEBPACK_IMPORTED_MODULE_0__bus__["a" /* default */].$emit('users.here', users);
}).joining(function (user) {

    __WEBPACK_IMPORTED_MODULE_0__bus__["a" /* default */].$emit('users.joined', user);
}).leaving(function (user) {

    __WEBPACK_IMPORTED_MODULE_0__bus__["a" /* default */].$emit('users.left', user);
}).listen('MessageCreated', function (e) {

    __WEBPACK_IMPORTED_MODULE_0__bus__["a" /* default */].$emit('messages.added', e.message());
});

bootstrap.js

require('./echo')

import Echo from "laravel-echo"

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: Laravel.keys.pusher,
    cluster : 'eu',
    encrypted : true
});

view part

   <script src=""></script>

    <script>

        window.Laravel = {!! json_encode([

            'csrfToken' => csrf_token(),
            'user' => [
                'authenticated' => auth()->check(),
                'id' => auth()->check() ? auth()->user()->id : null,
                'name' => auth()->check() ? auth()->user()->name : null
            ],

            'keys' => [
                'pusher' => config('broadcasting.connections.pusher.key')
            ]

        ]) !!};


    </script>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CjC4Tm
via IFTTT