samedi 30 septembre 2017

Laravel 5.5 dusk could not work

I make a new laravel project.

composer create-project laravel/laravel testing_laravel
composer require laravel/dusk --dev 
php artisan serve
php artisan dusk

and then...

PHPUnit 6.3.1 by Sebastian Bergmann and contributors.

F                                                                   1 /         1 (100%)

Time: 1.12 seconds, Memory: 10.00MB

There was 1 failure:

1) Tests\Browser\ExampleTest::testBasicExample
Did not see expected text [Laravel] within element [body].
Failed asserting that false is true.

/Users/nobuhiroharada/work/laracast/testing_laravel/vendor/laravel/dusk/src/Concerns/MakesAssertions.php:274
/Users/nobuhiroharada/work/laracast/testing_laravel/vendor/laravel/dusk/src/Concerns/MakesAssertions.php:245
/Users/nobuhiroharada/work/laracast/testing_laravel/tests/Browser/ExampleTest.php:20
/Users/nobuhiroharada/work/laracast/testing_laravel/vendor/laravel/dusk/src/TestCase.php:92
/Users/nobuhiroharada/work/laracast/testing_laravel/tests/Browser/ExampleTest.php:21

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Chrome browser is not lauching.

I am using.. macOS Sierra 10.12.1 localhost

"laravel/framework": "5.5.*", "laravel/dusk": "^2.0"

Google Chrome version: 61.0.3163.100 ChromeDriver 2.31.488774

Thank you very much for your help.



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

How can i access multiple row data in laravel5

I want to get multiple row data from table in controller . like i have a likes table columns are id and value i want to get like this statement . select * from likes where id is this and value is that .



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

merge css and scss in laravel mix

This is my code:

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'resources/assets/css')
   .styles([
     'resources/assets/css/animate.min.css'
   ],'resources/assets/css/style.css')
   .combine(['resources/assets/css/style.css','resources/assets/css/app.css'], 'public/css/app.css');

and results:

\js\app.js   928 kB

\resources\assets\css\app.css   185 kB

\resources\assets\css\style.css  52.8 kB

\css\all.css  52.8 kB

 You can see,It can merge app.css with style.css. output is only style.css as all.css

what is wrong?



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

Changing the type of last_activity column when using database session storage in Laravel 5.5

I've just started using the database session driver in Laravel 5.5 along with PostgreSQL, and I've ran into a slight inconvenience.

I would like to keep the last_activity column as timestamp with timezone, but Laravel wants to write an integer into it, and it sometimes also attempts to delete from it based on an integer value.

I tried doing the following in my Session model:

public function setLastActivityAttribute($ts){
    $this->attributes['last_activity'] = date('c', $ts);
}

which works well for saving, but when Laravel tries to garbage collect the sessions it uses an integer value which causes a PDOException:

SQLSTATE[22008]: Datetime field overflow: 7 ERROR: date/time field value out of range: "1506794381"
HINT: Perhaps you need a different "datestyle" setting. (SQL: delete from "sessions" where "last_activity" <= 1506794381)

Is there any way I could specify a format or intercept the process to keep the timestamptz column type?



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

how to get collaborators with project id in Laravel 5.2 in the localhost

I am developing project management application using Laravel 5.2. in My application side bar menus as sidebar.blade.php witch located in views\layouts\partials\sidebar.blade.php

<li><a href="#">Edit Account</a></li>
    <li><a href="">Projects</a></li>
    <li><a href="">Collaborators</a></li>
    <li><a href="#">Todos</a></li>

when I click project link in the sidebar pages view existing pages. and now I need add some collaborators to each project when click collaborators link in the sidebar. my collaborators form in view/collaborators/form

 <div class="col-md-4" style="border:1px solid #ccc;margin-left:15px;padding:10px;">
                <h4 class="page-header">
                    Collaborators
                </h4>
                <form class="form-vertical" role="form" method="post" action="">
                <div class="form-group">
                    <label> Add New </label>
                    <input type="text" name="task_name" class="form-control" id="name" value="">
                    @if ($errors->has('task_name'))
                        <span class="help-block"></span>
                    @endif
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-info">Add User</button>
                </div>
                <input type="hidden" name="_token" value="">
                </form>
</div>

my problem is this i need consider when I am in project 10 and I click collaborator link and then I need following localhost url

localhost:8000/project/10/collaborators

My existing routes is this
Route::get('/collaborators', function(){ 
   return view('collaborators.form'); 
})->name('collaborators.form');

but it is generated only localhost url as

http://localhost:8000/collaborators

how can I manages this?



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

Laravel - Call other package in my package

i'm creating my package for my develop. I create package name "News" and i want use multiple language so i use package "mcamara/laravel-localization". In main app, i had configed and website had worked. In my package, when i create route with same main App, it's reported "Class translator does not exist".

Please help me My route

Route::group(
[
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
],
function()
{
    /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
    Route::get('/', function()
    {
        return View::make('home');
    });

});

And my packageProvider

class NewsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        $this->loadMigrationsFrom(__DIR__.'/migrations');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        include __DIR__.'/routes.php';
        $this->app->make('Test\News\Controllers\NewsController');
    }
}



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

How to resolve the missing dependency in AuthServiceProvider of laravel while register passport routes

When I'm trying to print laravel routes with following command

php artisan route:list

It throws following exception

[Illuminate\Contracts\Container\BindingResolutionException]
Unresolvable dependency resolving [Parameter #0 [ <required> array $config ]] in class Jenssegers\Mongodb\Connection

if I remove the passport routes from my boot method then it works fine but of course passport routes are not getting printed.

here is my boot method:

public function boot()
    {
        $this->registerPolicies();

        Auth::provider('mongodb', function(Application $app, array $config){
            return new MongoDBUserProvider();
        });

        Passport::routes();

        Passport::tokensExpireIn(Carbon::now()->addDays(15));
        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

    }

And if i try to dd(DB::connection('mongodb')->collection('collection_name')->get()); it prints everything fine.



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

How to pass an array of data from controller to the view using laravel

There are two tables in my database. They are foods and sub_foods. I want to get the names of the sub_foods in Foods model as a array and pass it to the create.blade.php file for make a dynamic dropdown box inside the form. This is my code,

FoodsController.php

public function create()
{
    $sub_foods = ['' => ''] + Sub_food::lists('name','id')->all();
    return view::make('foods.create',array('sub_foods'=>$sub_foods));
}

create.blade.php

 <form action="/foods" method="post">
    
</form>



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

Laravel ajax deleting files fails

IN my vue js ajax post am storing file like

  $imagename = sha1(time()).".".$request->profile_pic->extension();
  $path = $request->profile_pic->storeAs('public/images/users',$imagename);
   $user = \Auth::user();
    //remove old file and retain new one
    if(\Storage::has($user->profile_pic)){
      \Storage::delete($user->profile_pic);
    }

   $user->picture = $path;
    $user->save();

THe above works and the image is saved in the storage/app/public/images/users which is okay

But the database field is saved as public/images/users so when accessing the value in the frontend its not found

After several tests i found out that in the database i need to save the file as

storage/images/users //note path is not starting with public

so i changed the

$user->picture="storage/images/users".$imagename;

But now after doing this the part that removes old file fails

if(\Storage::has($user->profile_pic)){
      \Storage::delete($user->profile_pic);
 }

How do i adjust the delete part to also work.



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

Laravel eloquent updateOrCreate(), do something only if create?

I use in my laravel 5.5 app Model::updateOrCreate(), it works, but by 1 parameter I wish to do something only if entry is creating and not updating model, is this possible?



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

Append Selected Drop Down Value with Option in Laravel Blade with Jquery

I want to show the models by changing the Drop Down value....I know how to get the value of drop down with change function but my problem is that i want to send that value in route to filter the models.....Please tell me how can i send the changed value id with route from blade..

This is my Drop Down

<select class="form-control" id="category" placeholder="Select category">
       <option>All</option>
       @foreach($categories as $category)
      <option value="?category="></option>
      @endforeach
</select>

Here i my Jquery Change Function

  $('#category').change(function(){
            alert($(this).val());
        })



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

Laravel 5.4 Accessors doesn't work

I have a User Eloquent model with attribute phone_1

here are method, but it does not work:

public function getPhone1Attribute($value)
    {
        xdebug_break();
        if ($value !== null) {
            return $this->formatPhone($value);
        }
        return $value;
    }



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

How does Laravel Contracts work

When I want to destroy a record,I only use the code like below

route

Route::resource('link-submit', 'LinkSubmitController', ['except' => ['show']]);

action

public function destroy(LinkSubmit $linkSubmit)
{
    if ($linkSubmit->delete()) {
        $key = 'ok_message';
        $message = 'delete ok';
    } else {
        $key = 'error_message';
        $message = 'delete fail';
    }

    return redirect()->back()->with($key, $message);
}

I found that when I use $link instead of $linkSubmit,it will not work. How Laravel get the parameters? Which file is the code in , I'm confused



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

Laravel make directory fails with storage_path

Am using faker an i would like to generate images and save them but am getting an error

mkdir(): No such file or directory

So i have

$factory->define(App\User::class, function (Faker $faker) {
$filepath = storage_path('images/fakerusr/'); //this fails
 if(!File::exists($filepath)){
     File::makeDirectory($filepath);  
 };
return [
    'profile_pic' => $faker->image($filepath,400,300)

];

});

BUt when i use

$filepath = public_path('images/fakerusr/'); //this works

But the path saved in the db starts from ./var/www... but i would like the path from images in the public folder.

I have added both read and write permissions to public folder

sudo chmod a+rw -R /var/www.../public

How do i go about this.



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

vendredi 29 septembre 2017

Using And where condition in Laravel model

What am trying to do is to use andWhere in my request

$passwordreset =  PasswordResets::where('token', $request->resetcode)
   ->andWhere('created_at','>',Carbon::now()->subHours(2))//error due to and
   ->first();

But the above returns an error.How can i perform this using the Model not DB:table since i would like a standard way of writing my code just by using the model.



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

Laravel using Ajax Creating default object from empty value

Iam Trying to update my form using AJAX POST method in laravel, while submitting the form am getting error as follow (Creating default object from empty value Laravel).
Here below my code:
Here my Ajax call:

        $('.submit').click(function(){
                $.ajaxSetup({
                    headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                });
            var form = $('form')[0];
            var update = new FormData(form);
            var id =$('.designNo').val();
         $.ajax({
            type:"POST",
              url:"/design_update/"+id,
                processData: false,  // Important!
                contentType: false,
                cache: false,
              data:update,
              success:function(results){
                if (results==1) {
                    $("#result").html("Upadated Successfully");
                    $('#result')[0].scrollIntoView(true);
                    $("#result").addClass("alert alert-success"); 
                      window.setTimeout(function(){
                      window.location.href = "/design";
                      }, 2000);
                  }else{
                    $('#error').html(results);
                    $('#error')[0].scrollIntoView(true);
                    $('#error').addClass("alert alert-danger");
                    }
                }
            }); 
        }); 

Here my Laravel Controller page :

public function update(Request $request, $id)
{
    // To Update
    // $validator = Validator::make($request->all(), [
    $this->validate($request,[
        'design_no'=>'required',
        'design_image'=>'image|nullable|max:1999'
    ]);
            // Handle file Upload
     if ($request->hasFile('design_image')) {
        // Get filename with image 
            $filenameWithex=$request->file('design_image');
        // Get just file name
             $filename=$_FILES['design_image']['name'];
            // $filename=pathinfo($filenameWithex,PATHINFO_FILENAME);
        // Get just ex 
            // $extension=pathinfo($filenameWithex,PATHINFO_EXTENSION);
        // File Name To Store
            $fileNameToStore=$filename;
        // Upload Image
            $path=$request->file('design_image')->storeAs('public/images',$fileNameToStore);
    }else{
        $fileNameToStore='noimage.jpg';
    }
    $design=design::find($id);
    $design->design_no=$request->input('design_no');
    $design->desg_1=$request->input('desg_1');
    $design->design_image=$fileNameToStore;
    $design->desg_2=$request->input('desg_2');
    $design->desg_3=$request->input('desg_3');
    $design->desg_4=$request->input('desg_4');
    $design->desg_5=$request->input('desg_5');
    $design->desg_6=$request->input('desg_6');    
    $design->save();
    return '1';
}  

Pls Help me to fix it ,Thanks in Advance



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

Markdown Laravel printing html code

I have installed Laravel Markdown but still printing HTML code.

my model

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use GrahamCampbell\Markdown\Facades\Markdown;
use Illuminate\Support\HtmlString;


class Post extends Model
{

    public function getContentHtmlAttribute($value)
{

     return Markdown::convertToHtml(e($this->content));

}
}

my blade page

{!! $post->content_html !!}

printing

<h2 style="font-family: DauphinPlain; line-height: 24px; 
color: rgb(0, 0, 0); margin: 0px 0px 10px; font-size: 24px; 
padding: 0px;">What is Lorem Ipsum?

Thank you



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

Laravel. Cron work only 1 time

I tryed to start cron in Laravel, what writo time ( Log::info(time()."\r\n");) to log file. I made next steps in console - console

It worked, but only 1 time. Only 1 time programm write time to log file, but in schedule file I put

$schedule->command('command:addToDB')->everyMinute();

My handle function looks like

public function handle()
{
    Log::info(time()."\r\n");
}

Can somebody help me with this problem?



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

Laravel 5.1 - Get artisan arguments from internal call

I do

when I run artisan queue:work or artisan queue:listen it runs the current commands with their corresponding Arguments. Now my question is, how can I Access those Arguments?

As you can see in the following Picture, the Arguments are there but I have no clue how to Access them?

enter image description here



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

PHP Access JSON object inside api response

I am asking for and receiving a response to an Http call to a cloud document storage service (ShareFile): the full response is below.

HTTP/1.1 100 Continue HTTP/1.1 200 OK Cache-Control: private Content-Length: 313 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/8.5 X-AspNet-Version: 4.0.30319 Access-Control-Allow-Origin: * Access-Control-Max-Age: 3628800 Access-Control-Allow-Headers: content-type Access-Control-Allow-Methods: OPTIONS, TRACE, GET, HEAD, POST Date: Fri, 29 Sep 2017 20:42:28 GMT X-SF-Server: storageCenter_HTTP/i-0d49984868dfc0715_172.16.100.22_us-east-1b Strict-Transport-Security: max-age=16000000; includeSubDomains; preload; {"error":false,"value":[{"uploadid":"6dba8852-b99a-4c2a-bc31-87d3ae26e3b0","parentid":"fo9b28ee-49fd-4812-9cdb-3d461e88a55a","id":"fif90a81-6c28-68f2-95ac-36a2e8d34639","filename":"TinManWoodProducts-bid75.pdf","displayname":"TinManWoodProducts-bid75.pdf","size":579398,"md5":"aee1fa760cf230340652b2ee130133ba"}]}

As you can see there is a json object nestled in there and I cannot figure out how to burrow in and retreive the json object. What I am particularly looking for is the "id":"fif90a81-6c28-68f2-95ac-36a2e8d34639".

I have tried json_decode($upload_response, true) which returns a null object, I have used utf8_encode (which makes no difference at all) and I have tried Laravel's ->json() (error - call to member function json() on string), and several other solutions to almost similar issues posted on stack overflow, but I still have no idea how to dig in and get the "id".

Php v:7.0.22 Laravel v:5.4

Any help greatly appreciated.



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

How to handle front end dependencies paths in laravel?

I have a project in laravel, in which I want to use specific paths for resources (e.g: i have some resources in aws s3 and cloudfront), in the same way as asset() does. So i created a provider that loads the php helpers in specific folder with this code:

File: app/Providers/HelperServiceProvider.php:

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    public function register()
    {
        // esto carga todo en Helpers!! use with caution :)
        foreach (glob(app_path() . '/Helpers/*.php') as $filename) {
            require_once $filename;
        }
    }
}

so i added it in providers array at config/app.php. Then I can define a function that is used in the templates to generate url to external paths:

<!DOCTYPE html>
<html>
    <head>
        <title>
            AppName - @lang('auth.title')
        </title>
        <link href="{!! my_asset('asset/in/S3.png') !!}" rel="stylesheet"/>
    </head>

I think this form is a bit out of the way things are done in laravel. Also I do not want to use preprocessors in js using node.js or laravel elixir to compile the assets and upload it to the cloud (and generate routes), because they add too much complexity to the project.

I wonder if there is a way more like laravel to handle the dependencies with external paths. Thanks



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

Laravel return collection with relation and with calculation

I have a laravel application which has a model Client.

A client has many addresses, many jobs and many transactions.

I've the following relations on my client model:

public function jobs()
    {
        return $this->hasMany('App\Job','client_id');
    }

public function addresses()
    {
        return $this->hasMany('App\Address','client_id');
    }

public function Fees()
    {
        return $this->hasMany('App\Transaction','client_id');
    }

I then have another function on that model which calculates the value

public function balance() 
    {
        return $this->Fees()->where('status',2)->sum('gross');
    }

I'm trying to return a list of all clients along with their addresses, jobs and the balance of each client.

I've tried the following:

 $customers = $user->clients()->with('balance')->with('jobs')->with('addresses')->get();

I get the following error

Call to a member function addEagerConstraints() on string

This will no doubt be the eagerloading and the fact the balance() isn't a collection but I'm wondering how I would achieve the same result without having to loop through to build an array.



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

Select element not displaying Laravel vaildation errors

i never had this problem before i have a select element with option and in my controller i set it to required and for some reason the validation error does not display the has error class doesn't even get added to the form-group

html and blade

<div class="form-group ">
       <label for="Return_Type">Return Type <span class="request-alert"></span></label>
         <select name="Test" id="Return_Type" class="form-control">
              <option>Choose One...</option>
                  @foreach($categories as $category)
                     <option value=""></option>
                  @endforeach
          </select>
          @if($errors->has('Test'))
             <span class="help-block">
                  
             </span>
           @endif
</div>

controller

 $this->validate($request, [
            'First_Name'    => 'required',
            'Last_Name'     => 'required',
            'Email'         => 'required',
            'Phone'         => 'required',
            'Fax'                        ,
            'Company'                    ,
            'Marketplace'   => 'required',
            'Order_Number'  => 'required',
            'Address_1'     => 'required',
            'Address_2'                  ,
            'City'          => 'required',
            'State'         => 'required',
            'Zip_Code'      => 'required',
            'Test'          => 'required',
            'Product_Name'  => 'required',
            'Quantity'      => 'required',
            'SKU'           => 'required',
        ]);



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

Pass an attribute and it's value to a rule in a request

So I have a basic form, let's say for example:

<form action="" method="POST" role="form">
    <legend>Form title</legend>

    <div class="form-group">
        <label for="">label</label>
        <input type="text" name="main" class="form-control" id="" placeholder="Input field">
    </div>

    <div class="form-group">
        <label for="">label</label>
        <input type="text" name="test" class="form-control" id="" placeholder="Input field">
    </div>  

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

Now, inside my controller's method, I am using a request:

public function store(CreateTestRequest $request)
{

}

Now, inside my request file, I have a rule for let's say the test input:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'main'      => 'required',
        'test'      => [
            'required',
            'numeric',
            new \App\Rules\Account\MyCustomRule,
        ],
    ];
}

Inside myCustomRule, I am trying to access, both the main's attribute and value, and the test's attribute and value, I can acccess the test's one by default, but I am not sure how to pass the other input's name and value to my custom rule... Is this possible? If so, how can I achieve this?

<?php

namespace App\Rules\Account;

use Illuminate\Contracts\Validation\Rule;

class MyCustomRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        dd($value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Sorry. ';
    }
}



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

Laravel View Composer dublicating SQL queries for every view

So I need to access some data (User details) in most views. What I have done:

I created ComposerServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            ['includes.header','profile'],
            'App\Http\ViewComposers\CustomerComposer'
        );

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Created CustomerComposer class

<?php

namespace App\Http\ViewComposers;

use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Modules\Customers\Entities\CustomerDetail;

class CustomerComposer
{
    public $customer = [];

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $user = Auth::guard('customer');

        $this->customer = CustomerDetail::where('user_id',$user->id())->first();

        $view->with( 'customer', $this->customer );
    }
}

Everything works but when I look at Debug bar it shows me same queries excecuted per view, so for example if I define ['includes.header','profile'] Same SQL will be excecuted twice if ['includes.header','profile','something_else'] 3 times and so on...

In this case query's is

select * from `customer_details` where `user_id` = '1' limit 1
select * from `customer_details` where `user_id` = '1' limit 1

If I provide wildcard in

view()->composer(
            ['*'],
            'App\Http\ViewComposers\CustomerComposer'
        );

It will generate 23 queries! I missed something here?



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

Laravel /page works /page/ redirects to other page

I have a Laravel website running on Apache server with WordPress

My WordPress installation is the root example.com/ And my Laravel App is the example.com/tools

If I access http://ift.tt/2yLNmLJ everything works fine, but if I access http://ift.tt/2yyxDi2 I get redirected to example.com/page/

Any ideas on what could be happening?

This is my web.php:

Route::get('/page/','PageController@index');

Thanks



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

SQLSTATE[42S02]: Base table or view not found

I am using Laravel Auth to register and login my users into the respective dashboard. I am using admin as my user. I created the migration for admin, but when i try to register my admin error comes Table or view not found and the table which is not found is the built in table users which i deleted because i was not using that one. I have to use the admin table please help me how can i remove this error.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fyp.users' doesn't exist (SQL: select count() as aggregate from users where email =**********)



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

Error while migrating inn laravel 5.4

I am trying to migrating tables in laravel. The error which is coming is

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 29 File '.\fyp\migrations.MYD' not found (E
rrcode: 2 - No such file or directory) (SQL: select `migration` from `migra
tions` order by `batch` asc, `migration` asc)



 [PDOException]
 SQLSTATE[HY000]: General error: 29 File '.\fyp\migrations.MYD' not found (E
 rrcode: 2 - No such file or directory)

Please tell me whats wrong with this.



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

Validate that each comma separated value exists in database?

Using Laravel 5.4, my users have an auto-complete helper to put values into an input. I want to validate that each of the values exists in the database when inserting.

Inputted value for "unit" : "12,13,14"

How do I check that, unit "12" and unit "13" and unit "14" exist in the database before doing the insert?

$units = array_filter(array_unique(explode(",", $request->unit))); 
 // input "12,13,14" becomes [12,13,14]

$this->validate($request,[
        'unit'  => 'required|exists:units.id,'.$units,
]);

Do I have to use a custom validation rule, or does laravel have something handy like 'required|existsAllValuesInThisArray' sorta thing? Haven't found anything in documentation about it.


I also found this, but it's for like multiple select fields or checkboxes sorta thing from the looks of it.

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);



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

laravel whereHas results weird

product model

    public function country() {
        return $this->hasMany('App\Models\ProductCountry', 'product_id', 'id');
    }

the controller

$product = Product::where('mall_' . $this->mall_id, '=', 1)
    ->whereHas('country', function ($i) use ($me) {
        return $i->where('country_id', $me->country_id);
    })
    ->find($key);

the raw SQL:

select * from `product` where `mall_3` = '1' and exists (select * from `product_country` where `product_country`.`product_id` = `product`.`id` and `country_id` = '109') and `product`.`id` = '3' and `product`.`deleted_at` is null limit 1

above SQL return no results(when the product id = 3

below SQL return the correct result(when the product id = 6)

select * from `product` where `mall_3` = '1' and exists (select * from `product_country` where `product_country`.`product_id` = `product`.`id` and `country_id` = '109') and `product`.`id` = '6' and `product`.`deleted_at` is null limit 1

have no idea, the query look like no problem

enter image description here enter image description here



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

Laravel sync throws integrity exception even if extist

I'm trying to link all my TicketMethod objects to all the Event objects:

foreach (Event::all() as $event) {
   $event->ticketMethods()->attach([1, 2]);
}

The 1 and 2 are the only ids in the db for TicketMethod.

In my Event I have the following code:

public function ticketMethods()
{
        return $this->belongsToMany('App\Models\TicketMethod', 'event_ticket_methods');
}

Exception:

[Illuminate\Database\QueryException]                                         
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update   
  a child row: a foreign key constraint fails (`tickets`.`event_ticket_method  
  s`, CONSTRAINT `event_ticket_methods_event_id_foreign` FOREIGN KEY (`event_  
  id`) REFERENCES `events` (`id`) ON DELETE CASCADE) (SQL: insert into `event  
  _ticket_methods` (`event_id`, `ticket_method_id`) values (@/Y�� ���ʫB{�1�,  
   1), (@/Y�� ���ʫB{�1�, 2)) 

The event_id fields are in binary format, which causes the question marks.

I don't get the error, as the event exists as I just retrieved them...



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

Laravel Upload image by excel

Hello friends i want to upload students data by excel in laravel with laravel excel plugin and i want to uploade image with excel file (By local path or other) Please suggest me solution for this

i create a function which upload file on my local server but not working on server

$excel = Excel::load(Input::file('file'))->get();
        foreach($excel as $exc) {
            $data = $exc->all();
            $data['class_id'] = $id;
            $data['school_id'] = $class->school_id;
            if ($student = Student::firstOrCreate($data)) {
                if (File::exists($exc->image)) {
                    $destinationPath = 'uploads/schools/' . $class->school_id . '/' . $class->id . '/' . $student->id . '/'; // upload path
                    if (!file_exists($destinationPath)) {
                        mkdir($destinationPath, 0755, true);
                    }
                    $file  = file_get_contents($exc->image);
                    $fileName = str_slug(Carbon::now()->toDayDateTimeString()) . rand(11111, 99999) . '.jpg'; // renameing image
                    if(file_put_contents($destinationPath.$fileName,$file)) {
                        $student->image = $destinationPath . $fileName;
                        $student->update();
                    }
                }
            }
        }



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

can u guide me how can i send data into two tables in a single form for doing Create and Update

this is my likes model

class Like extends Model { protected $fillable = [ 'user_id','post_id','value', ];

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


    //$this->belongsTo(User::class);
    //return $this->belongsTo('App\User');
    //   return $this->belongsTo('App\User','id','user_id');

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


    //$this->belongsTo(User::class);
    //return $this->belongsTo('App\User');
    //   return $this->belongsTo('App\User','id','user_id');

}

Post.php

protected $fillable = [ 'user_id','content', 'live','post_on','likes' ]; protected $dates = ['post_on'];

public function SetLiveAttribute($value)
{
    $this->attributes['live'] = (boolean)($value);

}


public function getshortContAttribute(){
    return substr($this->content, 0, random_int(60,150)). '...';
}

public function SetPostOnAttribute($value){
    $this->attributes['post_on'] = Carbon::parse($value);
}


public function user()
{
    //$this->belongsTo(User::class);
    //return $this->belongsTo('App\User');
 //   return $this->belongsTo('App\User','id','user_id');
    return $this->belongsTo('App\User');


}
public function comment(){

    return $this->hasMany('App\Comment');
}
public function like()
{
    return $this->hasMany('App\Like');


    //$this->belongsTo(User::class);
    //return $this->belongsTo('App\User');
    //   return $this->belongsTo('App\User','id','user_id');

}

}

please help in this . i m confuse . i have used Method Field PUT in form .



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

laravel upload image info failing noob here

hi there guys im not very good a laravel iv started 5 days ago,so i'm trying to upload some image info it work when i leave the code like this i get only null on the map field ....rest works

<label class="label-main"></label>

                        <div class="row">
                            <label class="col-md-5 control-label"></label>
                            <input type="text" class="col-md-7 input-sm instant-edit" name="photo[exif][zresta]" placeholder="Set Camera" value=""/>
                        </div>

                        <div class="row">
                            <label class="col-md-5 control-label"></label>
                            <input type="text" class="col-md-7 input-sm instant-edit" name="photo[exif][zcity]" placeholder="Set city" value=""/>
                        </div>

                        <div class="row">
                            <label class="col-md-5 control-label"></label>
                            <input type="text" class="col-md-7 input-sm instant-edit" name="photo[exif][wcountry]" placeholder="Set Focal Length" value=""/>
                        </div>

but when i change the code to this

<label class="label-main"></label>

                        <div class="row">
                            <label class="col-md-5 control-label"></label>
                            <input type="text" class="col-md-7 input-sm instant-edit" name="photo[exif][wrest]" placeholder="Resta" value=""/>
                        </div>

                        <div class="row">
                            <label class="col-md-5 control-label"></label>
                            <input type="text" class="col-md-7 input-sm instant-edit" name="photo[exif][zcity]" placeholder="Set Lens" value=""/>
                        </div>

                        <div class="row">
                            <label class="col-md-5 control-label"></label>
                            <input type="text" class="col-md-7 input-sm instant-edit" name="photo[exif][zcountry]" placeholder="Set Focal Length" value=""/>
                        </div>

the upload says upload fail

my img_info

class ImageInfo extends Model

{

use SoftDeletes;
/**
 * @var string
 */
protected $table = 'image_info';
/**
 * @var array
 */
protected $fillable = ['whatrest', 'wcity', 'wcountry', 'latitude', 'longitude'];

/**
 * @return array
 */
public function getDates()
{
    return ['created_at', 'updated_at', 'deleted_at'];
}

/**
 * @return mixed
 */
public function image()
{
    return $this->belongsTo(Image::class);
}

}

my upload` $exif = [ 'blah' => (isset($exif['blah']) && strlen($exif['blah']) > 0 ? $exif['blah'] : null), 'blahhh' => (isset($exif['blahhh']) && strlen($exif['lens']) > 0 ? $exif['lens'] : null), 'blahhh' => (isset($exif['blahhh']) && strlen($exif['blahh']) > 0 ? $exif['blahh'] : null),

        'latitude'      => $latitude,
        'longitude'     => $longitude,
    ];`



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

How to Load Laravel 5 settings on a Custom PHP Script?

I'm writing a script which is not using the whole Laravel Environment, so ideally I only need some bits of the whole framework.

I need to fetch the settings in the .env files and possibly be able to use the database via the query builder (http://ift.tt/2xCKG5c) instead of the ORM.

Any suggestion on how can I do it?



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

Filter collection using like and wildcard

I need to get all files which starts with desired letter, I'm trying to use a ->where filter adding 'like' as operator but wildcards doesn't work.

        $files = File::files(storage_path($id_files));
        $files = collect($files);
        $files->transform(function ($item, $key){
            $item->public_filename = $item->getFilename();
            return $item;
        });

This is our target data, I need to create a public_filename field to apply filters to. Our files (dd($files)):

   Collection {#503 ▼
  #items: array:3 [▼
    0 => SplFileInfo {#525 ▼
      -relativePath: ""
      -relativePathname: "atxt.txt"
      path: "/home/vagrant/Code/ceteis/storage/app/uploads/general"
      filename: "atxt.txt"
      basename: "atxt.txt"
      pathname: "/home/vagrant/Code/ceteis/storage/app/uploads/general/atxt.txt"
      extension: "txt"
      realPath: "/home/vagrant/Code/ceteis/storage/app/uploads/general/atxt.txt"
      aTime: 2017-09-29 09:51:17
      mTime: 2017-09-27 14:39:11
      cTime: 2017-09-27 14:39:11
      inode: 32833
      size: 3
      perms: 0100777
      owner: 1000
      group: 1000
      type: "file"
      writable: true
      readable: true
      executable: true
      file: true
      dir: false
      link: false
    }
    1 => SplFileInfo {#524 ▼
      -relativePath: ""
      -relativePathname: "batxt.txt"
      path: "/home/vagrant/Code/ceteis/storage/app/uploads/general"
      filename: "batxt.txt"
      basename: "batxt.txt"
      pathname: "/home/vagrant/Code/ceteis/storage/app/uploads/general/batxt.txt"
      extension: "txt"
      realPath: "/home/vagrant/Code/ceteis/storage/app/uploads/general/batxt.txt"
      aTime: 2017-09-29 09:51:31
      mTime: 2017-09-27 14:39:11
      cTime: 2017-09-27 14:39:11
      inode: 32834
      size: 3
      perms: 0100777
      owner: 1000
      group: 1000
      type: "file"
      writable: true
      readable: true
      executable: true
      file: true
      dir: false
      link: false
    }
    2 => SplFileInfo {#526 ▼
      -relativePath: ""
      -relativePathname: "txt.txt"
      path: "/home/vagrant/Code/ceteis/storage/app/uploads/general"
      filename: "txt.txt"
      basename: "txt.txt"
      pathname: "/home/vagrant/Code/ceteis/storage/app/uploads/general/txt.txt"
      extension: "txt"
      realPath: "/home/vagrant/Code/ceteis/storage/app/uploads/general/txt.txt"
      aTime: 2017-09-27 14:39:11
      mTime: 2017-09-27 14:39:11
      cTime: 2017-09-27 14:39:11
      inode: 5438
      size: 3
      perms: 0100777
      owner: 1000
      group: 1000
      type: "file"
      writable: true
      readable: true
      executable: true
      file: true
      dir: false
      link: false
    }
  ]
}

What I'm trying:

dd($files->where('public_filename','like','t%')); // 0 results

dd($files->where('public_filename','like','txt.txt')); //If I ommit wildcard and look for full name it retrieves correct file

So our target is:

dd($files->where('public_filename','like','t%')); // 1 result

Any idea? Could we use wildcards to filter a collection by using a like operator? Thank you guys!



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

Redirect issue in middleware for admin login in Laravel

When login to admin,then page is redirect But 'The page isn't redirecting properly' message show. Please help me

Middleware  - IsAdmin.php

    public function handle($request, Closure $next)
    {

         if (Auth::user()->role_id == 1)
        {
            return redirect ('/administrator');
        }

               return $next($request);
    }

web.php

Route::group(['prefix'=>'administrator','as' => 'admin.','middleware' => ['auth'],'middleware' => 'isAdmin'], function(){

    Route::get('/','AdminController@index');

    Route::resource('user','AdminController');

    Route::resource('card','AdminCardController');

});

Thanx in advanced..



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

whereBetween() Eloquent returning wrong results

Hi I have a eloquent query and I am using query scope. I have a km column in my table and I am passing kmFrom and KmTo values as post data. Now I am doing a eloquent whereBetween and its returning wrong results when I search for km.

For example if I pass kmFrom = 1000 and kmTo = 2000. Its giving me results which are not in between these two values.

Eloquent -:

```

Product::categoriesCategoryId($categoryId)
            ->km($kmFrom, $kmTo)->get();

```
Query Scope for the km -:

```

 public function scopeKm($query, $kmFrom, $kmTo)
    {   
        if(($kmFrom) && ($kmTo)){
            return $query->whereBetween('km', ["$kmFrom", "$kmTo"]);   
        }
        return $query;
    }

``` Please assist what wrong I am doing.



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

jeudi 28 septembre 2017

How to access public AWS S3 bucket in laravel

I have a public S3 bucket called latheesan-public-bucket (for example) in AWS in the eu-west-1 region.

If I were to visit the following url in the browser (for example):

http://ift.tt/2ybiPK6

I get the following XML showing that I have one file in the bucket:

<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://ift.tt/1f8lKAh">
    <Name>latheesan-public-bucket</Name>
    <Prefix />
    <Marker />
    <MaxKeys>1000</MaxKeys>
    <IsTruncated>false</IsTruncated>
    <Contents>
        <Key>test.json</Key>
        <LastModified>2017-07-11T16:39:50.000Z</LastModified>
        <ETag>"056f32ee5cf49404607e368bd8d3f2af"</ETag>
        <Size>17658</Size>
        <StorageClass>STANDARD</StorageClass>
    </Contents>
</ListBucketResult>

If I were to then visit http://ift.tt/2ybiQh8 I can download my file from my public bucket.

In order to achieve the same in my Laravel application; I first added this package via composer:

league/flysystem-aws-s3-v3

Then on my .env I've added the following lines:

AWS_REGION=eu-west-1
AWS_BUCKET=latheesan-public-bucket

Lastly, I then tried to use the laravel filesystem to access the public s3 bucket file like this:

$json = Storage::disk('s3')->get('test.json');

When I did this; I got the following error:

Error retrieving credentials from the instance profile metadata server. (cURL error 28: Connection timed out after 1000 milliseconds (see http://ift.tt/1mgwZgQ))

So, I updated my .env with some fake credentials:

AWS_KEY=123
AWS_SECRET=123
AWS_REGION=eu-west-1
AWS_BUCKET=latheesan-public-bucket

Now I get this error:

Illuminate \ Contracts \ Filesystem \ FileNotFoundException
test.json


So my question is; firstly what am I doing wrong here? Is there no way to access a public s3 bucket in laravel without actually providing a valid S3 Key/secret? what if I don't know them? I only have the url to the public s3 bucket.

P.S. the latheesan-public-bucket does not exist (it was a dummy bucket name to explain my problem, I do have a real public bucket I am trying to work with and it works fine in browser as explained above).



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

Laravel 301 Redirects

How can I get 301 Redirects to work with the public .htaccess file? It seems like it wont work because of the trailing backslash?

.hataccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    Redirect 301 /old-page/ http://www.mysite1.com
    Redirect 301 /old-page-1/ http://ift.tt/2xJBUlb
    Redirect 301 /old-page-3/ http://ift.tt/2xJBUlb
    Redirect 301 /old-page-4/ http://www.mysite1.com
    Redirect 301 /old-page/old-page/ http://ift.tt/2xJBUlb

</IfModule>

but it I change it for testing to say:

Redirect 301 /old-page/no-slash http://www.mysite1.com

that will redirect fine. The issue is I need those trailing slash since google has the old links that way.



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

Laravel component Basemkhirat how to pass a collection to a blade view

I've need use Basemkhirat for rapid development write for access data on ElasticSearch.

I don't understan well, system of pagination for this component, and and so I am trying to do the work in another way.

On my controller for the index, ProposalsController@index I get a collection

$proposals = ES::type('proposals')->take(200)->get();
dd($proposals);   

Dump exit:

Collection {#436 ▼
  #items: array:200 [▼
    0 => Model {#236 ▼
      #connection: "default"
      #index: "excellenting"
      #type: "proposals"
      #casts: []
      #attributes: array:25 [▼
        "doc_id" => 40005
        "source" => "epo"
        "date" => "20080801"
        "is_demand" => false
        "tech_category" => 40700
        "country" => "TW"
        "external_doc_code" => "TW200831462A"
        "title" => "Processes suitable for producing macromolecular antioxidant compositions"
        "abstract" => "This invention relates to processes for the production of reaction mixtures, which find use as antioxidants in a variety of applications, using sterically hinde ▶"
        "requirements" => null
        "url" => null
        "trl" => array:2 [ …2]
        "interest" => "any"
        "ip_status" => "granted"
        "tech_categories" => array:3 [ …3]
        "applicants" => array:1 [ …1]
        "inventors" => array:1 [ …1]
        "references" => array:1 [ …1]
        "singularities" => array:2 [ …2]
        "main_tags" => null
        "secondary_tags" => null
        "_index" => "excellenting"
        "_type" => "proposals"
        "_id" => "CwmpXd94idHxJ4EfyNBT"
        "_score" => 1.0
      ]
      #exists: true
      #appends: []
      +"_id": "CwmpXd94idHxJ4EfyNBT"
    }
    1 => Model {#239 ▶}

For blade template, I need use #attributes of array #items.

But if I only try this, fails:

return view('proposals.index', $proposals);

Blade

@forelse ($proposals as $proposal)
   <li></li>
@empty
   <p>No fatents found</p>
@endforelse

Error

 ErrorException (E_ERROR)
Undefined variable: proposals (View: /Users/abkrim/Sites/warehouse/resources/views/proposals/index.blade.php)



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

A non-numeric value encountered Laravel5.5 on Migration

I am getting this error [ErrorException] A non-numeric value encountered when I give an artisan command php artisan migrate:fresh --seed.

This issue arised when I upgraded to php 7.1 in xammp.

Is there a workaround on this issue?

Thanks in advance



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

Vue js 2 : How to filter array without mutation?

I have a very simple Laravel /Vue js website, i have a list of product wich i would like to filter.

const app = new Vue({
el: '#main-content',
data: {
    forfaits: window.forfaits,
},
methods: {
   filterData: function (val) {
        console.log(val)
        this.forfaits = this.forfaits.filter(item => {
          return item.internet >=val[0] && item.internet <= val[1] ;
      });
      return this.forfaits;

  }

HTML

 <div class="product-item offre" v-for="forfait in forfaits">
 .....
 ..... 
 .....

In this case it works but the original product array (forfaits) is mutated. How can i Filter without mutating the original value ?



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

MethodNotAllowedHttpException, when visiting correct(?) route

When I visit route A, a page is shown with a form with an action path to route B. When visiting this page I get the following error:

MethodNotAllowedHttpException
in RouteCollection.php (line 251)
at RouteCollection->methodNotAllowed(array('POST'))
in RouteCollection.php (line 238)

et cetera.....

ROUTE A

Route::get('to/connector/{id}/edit', [
    'as' => 'connector.edit',
    'uses' => 'Connector\ConnectorController@edit'
])->middleware('can:update-application-settings');

ROUTE B

Route::post('to/connector/{id}', [
    'before' => 'csrf',
    'as' => 'connector.update',
    'uses' => 'Connector\ConnectorController@update'
])->middleware('can:update-application-settings');

However, as soon as i delete {id} from ROUTE B no error is shown. I really don't understand why this is going wrong, as this method works for other routes. Could someone please tell me what is going wrong?

If more information is needed, please let me know.

Request header

enter image description here



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

Laravel moment js time zone issue

In my laravel vue js app, I am inserting data using eloquent and create_at time is automatically populated by laravel. In my front end I am trying to show the create_at time as 'ago' time using moment js and for that I am using vue-moment.

This is how I am trying to show in my view

But the problem is it's shows the 6 hours ago even if I create an item few seconds ago and for my friend who lives in different country shows 12 hours ago.

How can I make this time perfect for everyone from any country?

Thank you.



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

How Do I use/setup Bootstrap 4's Assets in my project files? Laravel

I have downloaded boostrap in my Laravel Project through Composer. I have all the package in: vendor/twbs/bootstrap/..... So how do I configure my boostrap to use in my php files? I tried with: php artisan vendor:publish --tag="vendor/twbs/boostrap/docs/assets"

There I have a question: Something must change/appear in my public folder? By default it has the following files:

Folders:

  • css Folder

    ->has app.config

  • js Folder

    ->has app.js

    Files: .htaccess, favicon, index.php, MyPage.php, robots.text and web.xml

And the bootstrap folder (vendor/twbs/boostrap/docs/assets) has 5 folders.



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

Overriding the migrations used in a package

I'm using Laravel Passport and added foreign key constraints to a migration. Now when I try to do migrate:reset I run into this error because I'm using PostgreSQL:

SQLSTATE[2BP01]: Dependent objects still exist: 7 ERROR:  cannot drop table oauth_clients because other objects depend on it
DETAIL:  constraint oauth_access_tokens_client_id_foreign on table oauth_access_tokens depends on table oauth_clients constraint oauth_auth_codes_client_id_foreign on table oauth_auth_codes depends on table oauth_clients
HINT:  Use DROP ... CASCADE to drop the dependent objects too.

This is easy to fix in my other migrations by simply making this my down statement:

DROP TABLE IF EXISTS some_table CASCADE;

However, to do this for the passport tables I need to be able to override the down() method of those migrations.

How do I prevent Laravel from using the migrations in the Passport package and instead only use the migrations in my main migrations dir?



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

Call to undefined function Illuminate\Encryption\openssl_cipher_iv_length()

I am getting this error. please help resolve it. enter image description here



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

error 422 (Unprocessable Entity) in laravel

I have a trouble when show error in laravel. I am using ajax to send request form from client to server and backward. This is my ajax code and seem to be function append() is not working.

$('#petition-form').on('submit', function(e) {
  e.preventDefault();
  var formdata = new FormData($(this)[0]);
  formdata.append('content', tinymce.get('content').getContent());
  $.ajax({
    url: $(this).attr('action'),
    data: formdata,
    processData: false,
    contentType: false,
    cache: false,
    method: 'POST'  
  }).done(function(response) {
   window.location.href = response.slug;
 }).fail(function(response) {
    $(this).append(parseJSON(response));
    // var getError = $.parseJSON(response);
  });

}); when console.log(response) it is array. anyone help me solve that. Thank u



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

Access blade variable as php variable in template

Working on a project using Blade 5.1. I know this isn't best practice as blade should just take care of view data. However, I need to template out a section that is in the master template. The master template has something like this:

<?php

function q($q) {$q['meta'] = @yield('meta');return $q;}
add_filter( 'document_title_parts', 'q' )

home.blade.php

@extends('layouts.master')

@section('meta')
    Hello world
@endsection

My question is, is it possible to access the section meta value passed in to the master template as a php variable? In simple terms, the goal here is to set $q['meta'] to 'Hello world' successfully.

Thanks in advance



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

Array to SVG, flexible algorithm with PHP

problem: I've a couple of different arrays - e.g.:

  • [0.21, 0.001, 0.0245, 0.31, 0.05, ...]

  • [1234, 1342, 1232, 1625, 2200, 2205, 1804, ...]

  • [5, 12, 42, 2, 32, 42, ...]

my problem now is: I'm looking for an algorithm to calculate a SVG Path for a simple chart like: simple Chart

my current problem is the general algorithm and the calculating of the viewbox for each SVG. Hope someone can help?



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

Laravel DB Migrations in custom package

I have some experience in Laravel but I'm still learning (currently I'm using 5.4). I'm creating my own package (which will have its own database tables, but one of the tables will be related with the users table of the "main" application).

I know I can load the migrations on my Package's Service provider:

public function boot()
{
    $this->loadMigrationsFrom(__DIR__.'/path/to/migrations');
}

But I see loads of pages/tutorials telling to publish those migration files. Is there any advantage on doing this?

Honestly I would prefer to keep the migration files inside the package, but I would like to know if there are any drawbacks on doing this before finishing my package and deploy it in production.

Thanks in advance



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

How to change default url from localhost:8000 to other Ip in laravel when we run "php artisan serve"

i am runnig "php artisan serve" command

by default result is -Laravel development server started: http://127.0.0.1:8000

i want to change pointing to other ip



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

Checking duplicated data in Laravel

This code work as send to "inn_db" table from "ext_db".

but it was not checked if the data is the same or different in inn_db. So there posited same values in "inn_db". How could I add that job? Thanks.

In Laravel-5.4, MySQL, InnoDB.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \DB;

class UpdateCustomerController extends Controller
{
    public function db_update()
    {
        $customers = \DB::connection('ext_db')->table('customers')->orderBy('customer_id')->chunk(1000, function ($all){
            foreach ($all as $kunde){
                DB::connection('inn_db')->table('custoemrs')->insert(
                    [$kunde->customer_id
                     $kunde->name,
                     $kunde->email]);
            }
        });
    }
}



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

composer require laravelcollective html 'doesnt download dependancy

please assist,

I am new to laravel and I cannot download dependency for laravelcollective/html ... I am using laravel 5.5.13

I want to require laravelcollective/html

however I face the following problems.

  1. when I run : composer require "laravelcollective/html:5.2.*",

I get the below mentioned(similarly when I run composer update ) :

C:\Users\MALULEKE\Desktop\lara_proj\shops>composer require "laravelcollective/html:5.2.*"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package laravelcollective/html could not be found in any version, there may be a typo in the package name.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <http://ift.tt/1QfuRiU; for more details.

Read <http://ift.tt/1g1ylKI; for further common problems.

Installation failed, reverting ./composer.json to its original content.

C:\Users\MALULEKE\Desktop\lara_proj\shops>composer require "laravelcollective/html:5.2.*"

below is my composer.json relative to my project's work (not from composer/roaming, I am not even sure which is it I must use, please help )

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "laravel/framework": "5.5.*@dev",
        "laravel/tinker": "~1.0",
        "laravelcollective/html":"~5.3.@dev"

    },
    "require-dev": {
        "filp/whoops": "~2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~6.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true

    }
}



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

Laravel: Writing to /.../.config/psysh is not allowed

I have installed a Laravel app locally using the Laravel Installer. Now I want to upload the app to my production server which is a managed virtual server, but it fulfills all the needed requirements.

I have uploaded the app and changed in the .env file the APP_URL and the DB_* settings accordingly. When I login to my server via ssh, go inside the app folder and try to use tinker

php artisan tinker

I get the following error message:

enter image description here

The error message makes sense, because the wp10*** folder does not contain a .config folder. However, I do not have permission to create folders at the same level as the www folder. Is it possible to put the folder inside the Laracast project folder? In my example this would be /is/htdocs/wp_10**/www/laracast/p1/.config/psysh. If so, how do I tell Laravel the new location?



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

Laravel only return records where the last item in a relationship equals requirements

I am working on some reporting for an app that has users and bookings.

The aim is to return all users that haven't made a booking within the last 2 months.

My query currently returns all users who has ever made a booking at the given team and order the bookings by newest to oldest.

My question is how can I only return users where the last booking made has an estimated booking time more than 2 months ago?

My current query is:

$collection = User::whereHas('customerBookings', function($q) use ($teamId) {
    $q->where('team_id', $teamId);
})->with(['customerBookings' => function ($q) use ($teamId) {
    $q->where('team_id', $teamId);
    $q->orderBy('estimated_booking_time', 'desc');
}])
->get();

This correctly returns all users that have bookings (relationship to a bookings table) that have the requested team_id and then only return the bookings that match the same requirements.

I was going to use ->reject on the collection but I would rather just filter out in the query itself.

Ideally I want to add something to the with claus:

$q->where( FIRST RELATIONSHIP ITEM ->estimated_booking_time, '<=', Carbon::now()->subMonths(2) );

The issue for me is how I can get the first item from the relationship and use it to only return the users depending on this last item.



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

Make quote as invoice using laravel

I am new to laravel framework. I have a small task to complete please anyone help me.

I have menus like quote,invoice etc.., In that quote I need option like view,edit, " INVOICE".,In quotes as make as invoice,Wen a user click it, the quote should be automatically change to invoice and add in the invoice list,So the status of this quote become invoiced.

Steps to achieve this is On click of the button open a store function in invoice or create a new function,They pass the quote is to that function on button click. And inside the function take the quote and quote products and save into invoice.

Kindly help me with code to finish my task.Thanks in advance

enter image description here



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

Extracting values from route Laravel

I want to retrieve contact_id and hash values from my route. In my PictureController I have pictures function where I want to use them.

My route:

Route::get('/static/contacts/{contact_id}/picture/{hash}', [ 'as' => 'platform.api.contacts.picture.hash', 'uses' => 'PictureController@pictures' ]);

I suppose this is not enough?

public function picture ($contactId, $hash)



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

How to fetch latest posts and specific post id at first in laravel eloquent

Is there way to fetch latest posts with pagination And I also want a specific post to first position in returned collection. I tried this...

Post::where(function ($query) {
    $query->where('status', 'draft')->orWhere('status', 'published');
})
->orWhere('id', 21)
->with(['author.profile'])
->orderBy('created_at', 'desc')
->paginate(3);

In this query I do get the 21 post id but it is on 3rd page. I want to get it on first place, I can I do this.

Thanks



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

trying to get property of non-object on laravel 5.4 constructor Auth::user()->id

I use Laravel 5.4.36. When I use Auth::user()->id on constructor method show me this error

(1/1) ErrorException
Trying to get property of non-object
in UserController.php (line 25)

My controller:

public function __construct()
{
    echo Auth::user()->id;

}  

But when I use Auth::user()->id on index method show me 2

    public function __construct()
{
    echo Auth::user()->id;

} 

result is : 2



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

what is the difference between Auth::routes() and Route::auth() in laravel

I have start working on laravel 5.4 , i have found that there is Auth::routes() which is called default in web route. I want to more clear with the difference between Auth::routes() and Route::auth().



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

mercredi 27 septembre 2017

Laravel Create a package with Service Provider and Facade -- Not Working

I'm trying to build a package that uses Guzzle, it started out as just a ServiceProvider, but after some research it looked like the best way was a small custom package.

However, due to my lack of experience with Laravel, I'm running into problems getting this working. At the moment I am getting the error:

Class zoho-api does not exist

Here is the package code below, I am hoping that someone can see where I've gone wrong/missed something and help steer me in the right direction. I've enjoyed the learning experience so far, be nice to get across the line.

Package is located here: api/packages/energynet/zoho

In the src folder:

ZohoServiceProvider.php

<?php

namespace EnergyNet\Zoho;

use Illuminate\Support\ServiceProvider;

class ZohoServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Perform post-registration booting of services.
     *
     * @return void
    */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([$this->configPath() => config_path('zoho.php')]);
        }
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom($this->configPath(), 'cors');

        $this->app->bind('zoho-api', function ($app){
            $client = new Client([
                'base_uri' => config('zoho.endPoint') . 'crm/private/' . config('zoho.defaultResponse')
            ]);
            return new ZohoApi($client);
        });
    }

    protected function configPath()
    {
        return __DIR__ . '/../config/zoho.php';
    }
}

ZohoApi.php

<?php

namespace EnergyNet\Zoho;

use GuzzleHttp\Client;

class ZohoApi
{
    protected $client;

    protected $authScope;

    public function __construct(Client $client)
    {
        $this->client = $client;

        $authScope = '?authtoken=' . config('zoho.authtoken') . '=' . config('zoho.scope');
    }

    public function ZohoLeads(){

        $response = $client->request('GET', 'Leads/getRecords' . $authScope);

        dd($response);
    }
}

ZohoFacade.php

<?php

namespace EnergyNet\Zoho;

use Illuminate\Support\Facades\Facade;

class ZohoFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'zoho-api';
    }
}

In config/app.php

'providers' => [
    ...,
     EnergyNet\Zoho\ZohoServiceProvider::class,
]

'aliases' => [
    'Zoho' => EnergyNet\Zoho\ZohoFacade::class
]

In composer.json

"autoload": {
     "psr-4": {
           "App\\": "app/",
            "EnergyNet\\Zoho\\": "packages/energynet/zoho/src"
      }

Then in LeadController.php

namespace App\Api\V1\Controllers;
...
use Zoho;

class LeadController extends Controller
{
    ...

    public function qualify(Request $request)
    {
         var_dump(Zoho::ZohoLeads());

Hopefully this is clear enough, any questions, please let me know. Really hoping someone can help. Thanks!



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

php artisan is not working in lavavel5.4 in XAMPP

i am trying to run PHP ARTISAN commands in cmd but the i am geting this error in CMD

[InvalidArgumentException]
Attribute [resouce] does not exist.

any thing i write with php artisan gives me this error like

php artisan make:model testModel
php artisan route:list

Complete error message is

C:\xampp\htdocs\laravel5.4>php artisan make:mode TestModel
[InvalidArgumentException]
Attribute [resouce] does not exist.

it was working fine i just maked a change in database directly like changed the role to role_id in user table after that it stops working



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

400 Bad Request When Adding Member to MailChimp List

I am sending a POST request to the following resource and getting a 400. I understand what the error means, but still am unsure why I'm getting it when a GET request to the same resource works.

/lists/{list_id}/members

Here is a exerpt of the code:

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', // <-- Drop in a GET here and it works, other than it's not the behavior I need.
    env('MAILCHIMP_API_URL') . 'lists/' . env('MAILCHIMP_LIST_KEY') . '/members',
    [
        'auth'  => ['app', env('MAILCHIMP_API_KEY')],
        'query' => [
            'email_address' => 'donnie@test.com',
            'email_type'    => 'html',
            'status'        => 'subscribed',
        ]
    ]);

dd($response->getStatusCode());



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

Middleware on route and in controller

I am attempting to run middleware on specific routes as well as inside controller constructor, however it appears middlewares that are defined inside the controller constructor are not being executed for the routes that include middleware. Is this not possible? (all of these middleware are registered in kernel.php, all middleware in constructor working before adding middleware to route)

Route

Route::get('/{organization_slug}', function($organization_slug){

    $organization = \App\Organization::where('slug', '=', $organization_slug)->first();

    $app = app();
    $controller = $app->make('\App\Http\Controllers\OrganizationController');
    return $controller->callAction('details', $parameters = array($organization->id));

})->middleware('verifyorganizationslug');

Controller Constructor

    public function __construct()
    {
        $this->middleware('auth', ['only' => ['create', 'update', 'store']]);
        $this->middleware('accountactive', ['only' => ['create', 'update', 'store']]);
        $this->middleware('ownsorganization', ['only' => ['update']]);
        $this->middleware('verifyorganization', ['only' => ['details']]);

    }



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

Lifespan of a class provided by Laravel Service provider

What is the life span of a custom class (whether singleton or non-singleton) created by custom laravel service provider?

My current understanding is that it gets created and destroyed every time user access a web page that needs the instance of this singleton class. Also it does not matter whether you have created PHP session or not. Meaning enabling user session does not impact the lifespan of the class provider by service provider.

Is this understanding right or wrong? I could not find a way to figure this out from current laravel documentation. Is there any documentation available that provides more elaboration on this subject?



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

Conditionally require authentication to access route in Laravel 5.4

In Laravel 5.4 I have a Page model and I would like to add a new field in DB to conditionally require authentication to browse the page.

So basically I want to serve pages, some pages will be accessible to everybody and some pages will require the user to be authenticated. If the user needs to be authenticated to view the page, he then will be redirected to the login page.

How can I implement this in Laravel?

I am thinking Gate but i am unsure how to mix both unauthenticated and authenticated rules..

Thanks guys!



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

What would be the consequences of passing all variables from controller to view?

What could go wrong if I always pass all variables to the view like this?

public function index(){
    $var1= '1';
    $var2= '2';
    $var3= '3';
    $var4= '4';
    $var5= '5';
    $var6= '6';

    return view('index',compact(array_keys(get_defined_vars())));
}



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

PBKDF2 SHA-256 in Laravel

Currently Laravel supports AES-256-CBC (http://ift.tt/2fAd2pM). However, I'd like to know if anyone out there know how to have it support PBKDF2 SHA-256 encryption instead?



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

how to fix Undefined variable: collaborators in Laravel 5.2 [duplicate]

This question already has an answer here:

in My laravel app. I have form.blade.php file in collaborator folder of view file. collaborators/form.blade.php

<div class="col-md-4" style="border:1px solid #ccc;margin-left:15px;padding:10px;">
        <h4 class="page-header">
            Collaborators
        </h4>
        @if( $collaborators)
           @foreach( $collaborators as $collaborator)
                <div>
                    <div>
                        <span>
                            <img src="" />
                        </span>
                    </div>
                    <button class="btn btn-sm btn-danger delete" style="margin-top:5px;padding:4px;width:35px;"
                      data-action="/projects//collaborators/"
                      data-token="">
                    <i class="fa fa-trash-o"></i>
                    </button>
                </div>
                <hr/>
           @endforeach
        @endif

it include with users.blade.php file in projects folder projects/users.blade.php

@include('collaborators.form')

but I got this error massages

Undefined variable: collaborators (View: C:\Users\Flex\Desktop\mati\resources\views\collaborators\form.blade.php)



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

Laravel 5.5 PHPunit Test - "A facade root has not been set."

When I do a try/catch on the DB::Connection()->getPdo();, I get the error A facade root has not been set. I believe it was happening with the Schema facades too before I tried adding the try/catch. The tests directory is, of course, outside of the app directory, and I have a feeling it has something to do with that, but I have not succeeded in figuring it out.

Here is the test class where this is happening:

<?php

namespace Tests\Models;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use App\Models\Discussion;
use App\User;
use Business\Database\Model;
use Illuminate\Database\Schema\Blueprint;
use Tests\TestCase;

class DiscussionModelTest extends TestCase
{
    /**
     * Create the tables this model needs for testing.
     */
    public static function setUpBeforeClass()
    {
        try {
            DB::connection()->getPdo();
        } catch(\Exception $e) {
            die($e->getMessage());
        }

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

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

        Schema::create('users', function (Blueprint $table) {
            $table->integer('id');
        });
    }
}



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

Cannot throw objects that do not implement Throwable

I am using Laravel 5.5. There is following class

vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php

with Method Name: buildException

In, Laravel 5.4, I was able to return JSON in this method like below.

protected function buildException($key, $maxAttempts)
{
    $retryAfter = $this->getTimeUntilNextRetry($key);
    $headers = $this->getHeaders(
        $maxAttempts,
        $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
        $retryAfter
    );
    return response()->json('429 Too many requests');
}

When I try to return JSON in above method using Laravel 5.5, it says

Cannot throw objects that do not implement Throwable

Now sure , how could I return JSON in Laravel 5.5 for above method



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

Force download from amazon s3 private file in laravel

Hello i have some problem with doing a force download. Here is my code :

public function download(Request $request, $id) {
  $document = Document::find($id);
  $s3 = Storage::disk('s3');
  $name = substr($document->link, strrpos($document->link, '/') + 1);
  $file = $s3->get($name);
  $headers = [
    'Content-Type' => 'application/pdf',
    'Content-Description' => 'File Transfer',
    'Content-Disposition' => "attachment; filename={$name}",
    'filename'=> $name
  ];
  return response()->download($file);
}

i don't get it how to access the good file

response :

is_file() expects parameter 1 to be a valid path, string given

Any ideas ?



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

The changes I made doesn't take effect on vue js laravel

I have a file named Notification.vue inside components folder.

From my app.js, I imported the notification.vue as below:

Vue.component('notification', require('./components/Notification.vue')); 

The above code is working fine.

However, when I made changes on Notification.vue, the expected output is not executing. Hence, I tried the following Attempts:

  1. I cleared my cache
  2. I executed php artisan cache:clear
  3. I deleted the file Notification.vue - (I expected an error on my console but none.)

But still, the output is still the same. No changes is seen on my site.

Does anybody know what's going on here and how to fix this? thanks



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

Laravel user active attribute

I have no clue if it even is possible but, If I add an "is_active" column to my user table. Can I make it work like the following? If the user is online, this turns to true so that I can make something in HTML like "Person active". And the same goes for if the individual goes offline. I somehow need to track if a person is online or offline and that for all registered users. How can I do this?

Tips are welcome! Thanks for taking the time to help me out.



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

Calling stored procedures in Laravel 5.5 using SQL Server with output

I have the following stored procedure:

declare @CodigoRet int

exec Generator 'LancaContaContabil', @Codigo = @CodigoRet output

Select @CodigoRet

  • OBS: the LancaContaContabil is my table and the Codigo is the PK for that table

And I'm trying to call this procedure in Laravel 5.5 but it gives me the error: "The active result for the query contains no fields":

$results = DB::select(DB::raw('DECLARE @CodigoRet INT; execute Generator 
\'LancaContaContabil\', @Codigo = @CodigoRet OUTPUT;'));
echo $results;
die;

Same error using the variant without dbraw:

$results = DB::select('DECLARE @CodigoRet INT; EXEC Generator         
\'LancaContaContabil\', @Codigo = @CodigoRet OUTPUT;');
echo $results;
die;

Also tried with statement, but the return is always 1:

$results = DB::statement('DECLARE @CodigoRet INT; EXEC Generator 
\'LancaContaContabil\', @Codigo = @CodigoRet OUTPUT;');
echo $results;
die;

EDIT: I created the procedure under the name 'testeproc' and now i've tried this, with the same error as above:

$results = DB::select('EXECUTE testeproc');
echo $results;
die;

What am I doing wrong?



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

Image Upload duplication

I am trying to allow users to upload three images(optional) when they make a review of the product. I am encountering a problem with the code below, which is that the images duplicate when the form is submitted which means that i sometimes get two of the same images or all three the same. Does anyone know the solution to this issue or a better way to do three image optional image uploads?

Html:








Laravel PHP:

 $picture = new Picture();
        if($request->hasFile('image')){
            $image = $request->file('image');
            $filename = time() . '.' . $image->getClientOriginalExtension();
            $location = public_path('images/' . $filename);
            Image::make($image)->save($location);
            $picture->image = $filename;
        }
        $picture->products()->associate($product);
        $picture->user_id = $request->user()->id;
        $picture->reviews()->associate($review);
    $picture->save();

    $picture2 = new Picture();
    if($request->hasFile('image2')){
        $image = $request->file('image2');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/' . $filename);
        Image::make($image)->save($location);
        $picture2->image = $filename;
    }
    $picture2->products()->associate($product);
    $picture2->user_id = $request->user()->id;
    $picture2->reviews()->associate($review;

    $picture2->save();
    $picture3 = new Picture();
    if($request->hasFile('image3')){
        $image = $request->file('image3');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/' . $filename);
        Image::make($image)->save($location);
        $picture3->image = $filename;
    }
    $picture3->products()->associate($product);
    $picture3->user_id = $request->user()->id;
    $picture3->reviews()->associate($review);

    $picture3->save();



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

What is the meaning of installing dependencies example laravel dependencies

I am new to the both php and laravel. I came to know that laravel is a php framework. Laravel uses composer to install dependencies. Here what is the meaning of dependencies.... Please explain in elaborate



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

import (import one from "./two") is not working in js file ( laravel 5.4 broadcasting Pusher)

Node Version 8.6.0

npm version 5.3.0

Chrome Error ( Version 61.0.3163.100 )

Uncaught SyntaxError: Unexpected token import

Mozila Error ( Version 56.0 (64-bit) )

SyntaxError: import declarations may only appear at top level of a module import one from "./two";



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

I'm getting an error when i send the reset mail to email. "Password resetter [users] is not defined."

laravel 5 reset email issue "Password resetter [users] is not defined". can anybody help me sorting my problem



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

Laravel delete method deleting all rows

I have an if statement that checks a request that contains an array of 'services' that are assigned to a user and then removes / adds them if they have a 'checked' value.

The issue I am currently having is that even when specifying a row using ->first and specific where values, it is deleting all of the rows in the database.

// Loop through all the services
foreach ($request->services as $key => $value) {
    $serviceRecord = ServiceUser::where('user_id', $userId)->where('id', $value['id'])->first();

    // The service is checked and it doesn't currently exist in the pivot table (not assigned to user)
    if ($value['checked'] && !$serviceRecord) {
        // Create an array of new values to be inserted

    // The service is not checked and does exist in the user_service table (currently assigned, wanting to be removed)
    } elseif (!$value['checked'] && $serviceRecord) {
        $serviceId = $serviceRecord->id;
        // $activeBookingsWithService is a count to see if the service can be deleted

        if (!count($activeBookingsWithService)) {
            $serviceRecord->delete();
        }
    }
}

This is a slightly stripped down version of the if statement. When trying to debug I can confirm:

  • $request->services only contains one item
  • $userId is the correct value
  • $serviceRecord only returns 1 value that is correct

Is there anything obvious that might explain why all rows are being deleted? I have also swapped out the deletion part and updated the row values instead which also updates all the records in the database.



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