dimanche 30 septembre 2018

Laravel 404 on production server NGINX

I have Laravel with NGINX on my production server, I have added new routes and they work fine on the localhost. But in production, it returns 404.

  1. I have restart NGINX but still no result.
  2. I look a the route list and they are present.

What is the problem and how can I fix it?



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

Add condition base on parent's parent data in laravel

I have a problem converting query to Laravel Eloquent. This is the query:

SELECT cat.id, reg.title as region_title, reg.region_code, catlang.title, catlang.description, cat.status from categories as cat join regions as reg ON cat.region_id = reg.id join category_language_region as catlang on cat.id = catlang.category_id and reg.language_id = catlang.language_id;

That is working in Postgres and as you can see, I added additional condition for joining category_language_region "reg.language_id = catlang.language_id". I'm stuck on converting it to Laravel Eloquent Builder.

This is the schema for it

  • Table Language: id, code
  • Table Region: id, code, language_id
  • Table Category: id, status, region_id
  • Table Category Language Region: id, title, category_id, language_id

This is what I tried

$results = Category::with([ 'region' => function($query){ $query->select('title', 'id', 'region_code', 'language_id'); }, 'categoryLanguages']) ->select(['categories.*']) ->whereIn('region_id', $region_ids);

But it returns all category language region. I need add to condition to select only category_language_region.language_id equal to selected region.language_id



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

Laravel query failed using function query

I am trying to get sum of amount of all users group by month.But if I add sum then query not work.It return amount log as blank array But without sum query return all logs data as monthly.

My query

$reports = $user->whereHas('groups', function ($query) use($acceptedGroup) {
    $query->whereIn('groups.name',$acceptedGroup);
})->with(
    array(
        'amountLogs' => function($query) use($year){
            $query
            ->select(
                DB::raw('sum(amount) as total')
            )
                ->whereYear('created_at','=',  $year)
                ->groupBy(DB::raw("MONTH(created_at)",'user_id'))->get();
        })
);

If I remove

            ->select(
                DB::raw('sum(amount) as total')
            )

Then query works



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

Images not being displayed after Transferred Laravel Website on server

I have transferred website from local to web server, mean while i changed some scenarios.

1- I have changed folder structure and moved public folder files on root.

2- Image files are being uploaded into store folder while symbolic storage folder is moved on root also.

But after moving public folder files on root images not working. while uploaded images are being stored into main storage folder. but not linked with symbolic storage folder. so help me how can i attach again both storage folders.

Storage folder related code into config/filesystem is shown below:

'disks' => [

'local' => [
    'driver' => 'local',
    'root' => storage_path('app/pulic/images/'),
],

'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],

's3' => [
    'driver' => 's3',
    'key' => env('AWS_KEY'),
    'secret' => env('AWS_SECRET'),
    'region' => env('AWS_REGION'),
    'bucket' => env('AWS_BUCKET'),
],

],

main storage folder path is:

Root/Laravel_files/storage/app/public/images

while symbolic storage folder address is:

Root/storage/images



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

Laravel query bulider: reverse of "LIKE"?

I need the reverse of a LIKE comparison. For example, if my database contains a person with firstName "Daniel" and I search for first name "dan" then I want to get a hit. The query works when I use

->where('firstName', 'like', '%'.$searchTerm.'%')

What would I use if my database contains "Dan" and I want to get a hit when I search for "Daniel"?

I am using the query builder in Laravel 5.6



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

Laravel insert and update to JSON not working

Can't figure out why JSON field is being ignored.

This one doesn't work:

Registries::create([
    'nr' => $old_document->no,
    'metas->name' => 'r01',
]);

In model I have set:

protected $casts = [
        'metas' => 'array',
    ];

And:

protected $fillable = [
        'nr',
        'metas'
    ];

I think the problem is in attributes casting, because this one is working:

Registries::create([
    'nr' => $old_document->no,
    'metas' => json_encode(['name'=>'r01']),
]);

I'm not getting any errors just JSON column stays empty.



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

Laravel: Failed to authenticate on SMTP server with username "xxx@xxxxx.com.au" using 2 possible authenticators

I am trying to send emails from my application using SMTP server. My mail settings in env file are as below -

MAIL_DRIVER=smtp 
MAIL_HOST=mail.xxxxx.com.au 
MAIL_PORT=465 
MAIL_USERNAME=xxx@xxxxx.com.au 
MAIL_PASSWORD=mySymbolicPassword 
MAIL_ENCRYPTION=ssl

When I use the gmail mail account settings, it works perfectly fine over mail port 587 and encryption to be TLS. When I change this to another mail server it fails with an error -

"Failed to authenticate on SMTP server with username "xxx@xxxxx.com.au" using 2 possible authenticators"

Is there anything I am missing here?



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

Laravel 5.6. How test racing conditions occurred during lockForUpdate()

I want to verify with my test in my application logic, that model with lock can't be selected and the whole logic "around" it performs as it should.

How to do it?

I've tried to use multiple nested transactions on different connections, but it did not give any result. I still can retrieve and modify columns in the second transaction.

DB::connection('pgsql1')->transaction(function () {
    factory(SomeModel::class, 5)->create();
    SomeModel::inRandomOrder()->lockForUpdate()->first();

    DB::connection('pgsql2')->transaction(function () {
        $this->assertEquals(4, SomeModel::count()); //fails, still 5 and should be 4 due to a lock on a random model
    });
});



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

Domain is currently unable to handle this request on a Laravel project

so I've been facing this problem all week and can't seem to figure out what the problem is.

Whenever I try to access my app online I get the following error.

[the-domain] is currently unable to handle this request.

I'm currently lost and don't even know what the problem is I've replicated my local environment on my server and the problem still persists, probably something I'm missing.

Here is my current config.

Laravel version: 5.7 PHP version: 7.2.9

Heres the stack trace form laravel.log:

[2018-09-30 12:18:28] staging.ERROR: syntax error, unexpected '|', expecting variable (T_VARIABLE) {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\F$
[stacktrace]
#0 /var/www/avanzi/vendor/composer/ClassLoader.php(322): Composer\\Autoload\\includeFile('/var/www/invite...')
#1 [internal function]: Composer\\Autoload\\ClassLoader->loadClass('Illuminate\\\\Supp...')
#2 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(22): spl_autoload_call('Illuminate\\\\Supp...')
#3 /var/www/avanzi/vendor/composer/ClassLoader.php(444): include('/var/www/invite...')
#4 /var/www/avanzi/vendor/composer/ClassLoader.php(322): Composer\\Autoload\\includeFile('/var/www/invite...')
#5 [internal function]: Composer\\Autoload\\ClassLoader->loadClass('Illuminate\\\\Data...')
#6 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Database/DatabaseServiceProvider.php(35): spl_autoload_call('Illuminate\\\\Data...')
#7 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(572): Illuminate\\Database\\DatabaseServiceProvider->register()
#8 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php(75): Illuminate\\Foundation\\Application->register(Object(Illumin$
#9 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(548): Illuminate\\Foundation\\ProviderRepository->load(Array)
#10 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php(17): Illuminate\\Foundation\\Application->registerConfi$
#11 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(206): Illuminate\\Foundation\\Bootstrap\\RegisterProviders->bootstrap(O$
#12 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(162): Illuminate\\Foundation\\Application->bootstrapWith(Array)
#13 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(146): Illuminate\\Foundation\\Http\\Kernel->bootstrap()
#14 /var/www/avanzi/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Ob$
#15 /var/www/avanzi/public/index.php(58): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#16 {main}
"}

Hope someone can help? Thanks in advance.



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

why dont accept the validation at laravel

   

> Blockquote  i have some promblem with validation thl1 when i insert two numbers 
it     
accept it but it have min:10 , when  i use 'thl1'=> 'required|min:10, without numeric 
it dont accept 2 or more  numbers but accept the letters,, in database 
thl1 is varchar(191) 

   public function updateProfile(Request $request){
    $user_id = Auth::user()->id;
    $this->validate($request, [
     'name' => 'required|string|max:25|min:3|alpha',
     'lastname' => 'required|string|max:25|min:3|alpha', 
     'username' => 'required|max:25|min:3|alpha_dash|unique:users,username,'.Auth::user()->id,
     'email' => 'required|string|email|max:55|unique:users,email,'.Auth::user()->id,
     'country' => 'required|min:3|alpha|max:30',
     'city' => 'required|min:3|alpha|max:30',
     'thl1' => 'required|min:10|numeric',
     'thl2' => 'min:10|numeric|nullable',
    
    ]);
    
    
    #validation.php
     'thl1' => [
            'min' => 'To Τηλέφωνο 1  πρέπει να περιέχει τουλάχιστον 10 χαρακτήρες. ',
           'numeric' => 'To Τηλέφωνο 1  πρέπει να περιέχει μόνο αριθμούς. ',
           'required' => 'Το Τηλέφωνο 1 είναι υποχρεωτικό',
        ],

        'thl2' => [
            'min' => 'To Τηλέφωνο 2  πρέπει να περιέχει τουλάχιστον 10 χαρακτήρες. ',
           'numeric' => 'To Τηλέφωνο 2  πρέπει να περιέχει μόνο αριθμούς. ',
        ],


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

L5.5 Create symlink between storage and public directories on shared hosting using SSH

I've setup my production server on a shared hosting my directory structure looks like this (my project is placed at same level as public):

/home/user/my-laravel-project/
/home/user/public_html

This is how I'm storing my data in Storage > Public Disc

$data->store('path/to/data', 'public');

On production, using SSH, when I run this command php artisan storage:link. It creates a symlink between storage/app/public and my-laravel-project/public I want this link to be created between storage/app/public and /home/user/public_html

What I've tried

  • Tried removing my-laravel-project/public then tried php artisan storage:link .. it failed with an error No file or directory
  • I tried changing storage path from storage_path('app/public) to public_path() under config/filesystem.php but no success
  • I've also tried to create symlink using shell command ln -nsf /home/user/my-laravel-project/storage/app/public /home/user/public_html but no success

Tried many other little tweaks but nothing works for me .. I'm looking for a proper solution to create a symlink between storage/app/public and /home/user/public_html on my shared server

Note I don't want to change paths in config/filesystems.php as that's not a proper solution

My current server is setup on Siteground with php version 7.0.32 and Laravel 5.5.43



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

Auth::check() is always false in middleware in Laravel 5.7

I have used middlewares for many Laravel applications, but this is a stupid situation never happened to me before. The middleware always returns false for Auth::check()

This is routes of User module

<?php
Route::group(['middleware' => 'web', 'namespace' => 'Modules\User\Http\Controllers'], function () {
    Route::get('/', 'UserController@index');
    Route::get('login', 'LoginController@showLoginForm')->name('login');
    Route::post('login', 'LoginController@login');
    Route::post('logout', 'LoginController@logout')->name('logout');
});
Route::group(['middleware' => 'admin', 'prefix' => 'user', 'namespace' => 'Modules\User\Http\Controllers'], function () {
    Route::get('register', 'RegisterController@showRegistrationForm')->name('register');
    Route::post('register', 'RegisterController@register');
});

This is AdminMiddleware inside the User module

<?php

namespace Modules\User\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $log = Auth::check();
        dd($log);
        return $next($request);
    }
}

and this is kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'admin' => \Modules\User\Http\Middleware\AdminMiddleware::class
];

But the result of dd($log) is always false. What is wrong here?!!!



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

values are not saving into database in laravel

I am trying to save my checkbox value but i dont know where i am wrong i am stuck in this issue my controller where i am performing my action:

Controller:

public function preferences(Request $request)
{
    $user = Auth::guard()->user();

    $preference = new Preference();

    $preference->userID = $user;
    $preference->monthly = Input::get('monthly') == 'on' ? 1 : 0;
    $preference->weekly = Input::get('weekly') == 'on' ? 1 : 0;
    $preference->tax_reviews = Input::get('tax_reviews') == 'on' ? 1 : 0;
    $preference->quarterly = Input::get('quarterly') == 'on' ? 1 : 0;
    $preference->quarterly = Input::get('quarterly') == 'on' ? 1 : 0;
    $preference->annually = Input::get('annually') == 'on' ? 1 : 0;
    $preference->newsletter = Input::get('newsletter') == 'on' ? 1 : 0;
    $preference->direct_mail_reviews = Input::get('direct_mail_reviews') == 'on' ? 1 : 0;
    $preference->email = Input::get('email') == 'on' ? 1 : 0;
    $preference->sms = Input::get('sms') == 'on' ? 1 : 0;
    $preference->save();

    return back();

}

My Form:

<form id="preferences_form" role="form" method="POST" novalidate action="" class="mujucet-registration">
                                <h5>Nastavení zpráv</h5>
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label  for="ch1">
                        <input type='hidden' name='monthly' value='0'>
                                                <input type="checkbox" name="monthly" value="1" id="ch1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Měsíční výpisy
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label>
                        <input type='hidden' name='monthly' value='0'>
                                                <input type="checkbox" name="weekly" value="1" ><span class="cr"><i class="cr-icon fa fa-check"></i></span>Týdenní přehled
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label>
                        <input type='hidden' name='tax_reviews' value='0'>
                                                <input type="checkbox" name="tax_reviews" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Daňové výpisy
                                            </label>
                                        </div>
                                    </div>

                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label>
                        <input type='hidden' name='quarterly' value='0'>
                                                <input type="checkbox" name="quarterly" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Čtvrtletní výpisy
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label>
                        <input type='hidden' name='annually' value='0'>
                                                <input type="checkbox" name="annually" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Roční výpisy
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label>
                        <input type='hidden' name='newsletter' value='0'>
                                                <input type="checkbox" name="newsletter" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Novinky
                                            </label>
                                        </div>
                                    </div>

                                    <div class="col-md-12">
                                        <div class="checkbox">
                                            <label class="border">
                        <input type='hidden' name='direct_mail_reviews' value='0'>
                                                <input type="checkbox" name="direct_mail_reviews" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span> Chci výpisy zasílat také Poštou <span class="light">20 kč za výpis</span>
                                            </label>
                                        </div>
                                    </div>

                                </div><h5>Kontaktní preference</h5>
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label>
                        <input type='hidden' name='email' value='0'>
                                                <input type="checkbox" name="email" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>Email
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="checkbox">
                                            <label>
                        <input type='hidden' name='sms' value='0'>
                                                <input type="checkbox" name="sms" value="1"><span class="cr"><i class="cr-icon fa fa-check"></i></span>SMS
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </form>                        </div>

My routes

Route::post('preference','HomeController@preferences');

My model where i am having my database name

class Preference extends Model
{
    protected $table = 'db_preferences';

    protected $fillable = ['userID','monthly','weekly','tax_reviews','quarterly','annually','newsletter','direct_mail_reviews','email','sms'];
}

i dont know why data is not inserting into database i click the submit button and page refresh and thats it and i am getting no error but data is not saving into db.

Your help will be highly appreciated!



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

best resource to learn authentication and authorization in laravel

i am creating a laravel project, in which i needs a lot of authentication and authorization. I go through all the basic stuff that is available on youtube, laravel.com and other websites. But i'm still confuse how to implement these in my project. I need a complete authorization and authentication resource, where i can learn these in a sequence and completly. Resource may be any book, website, youtube channel or else. Please reply me. thank you



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

How can I have my mobile view in a container-fluid and the desktop site in a container?

I'm building a website using laravel and bootstrap 3. When I apply a .container class the site displays well on medium and large screen sizes but too small on smaller devices like phones (with huge padding on both sides). And when I apply the .container-flud class, it displays well in smaller devices and covers the whole screen in large devices (which I don't want).

So what I want is to have the mobile view in container-fluid and medium and large screen view in a container. Is this possible? and how can I achieve this?

I'm using bootstrap 3

Any help is highly appreciated



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

How can I added comma in variable data?

I want to remove key and added comma after each value, I have tired with foreach but i coundn't sucuss.

$data = array:195 [▼
          0 => 26404.759765625
          1 => 26390.619140625
          2 => 26391.9609375
          3 => 26397.6796875
          4 => 26421.630859375
          5 => 26414.880859375
          6 => 26409.33984375
          7 => 26410.509765625
          8 => 26403.220703125
          9 => 26386.029296875
          10 => 26400.109375
          11 => 26412.369140625
          12 => 26408.099609375
          13 => 26418.029296875
          14 => 26422.80078125

I am trying with below loop :

foreach($data  as $key=>$value){
$dataes = $value
}
DD($dataes);

expected result should be like below:

    array:195 [▼
         26404.759765625,
         26390.619140625,
         26391.9609375,
         26397.6796875,
    so on...



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

Error when POSTing a form to auth route (MethodNotAllowedHttpException)

I am trying to POST a form BEFORE user authentication. User inputs data into a form and POST it to the route protected by auth:

Route::group(['middleware'=>'auth'], function(){ Route::post('v2/payment/start/','PaymentController@generic');

});

If a user IS authenticated BEFORE the POST, the request is processed OK. If a user is NOT authenticated, user gets the login form, enters login password and receives the error "MethodNotAllowedHttpException".

What could be the cause of this? In my LoginController I have:

return redirect()->intended($this->redirectPath());

so, the user should be redirected OK.

Where could be the error?



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

How to pass multiple parameter from Form to URL in Laravel?

I have a form which has multiple input, from which I want to pass values of input to URL

<form method="get" action="">
 <input type="text" name="age" >
 <input type="text" name="first_name" >
 <button type="submit">Submit</>
 </form>

Route::get('search/{age}/{first_name}', 'SearchController@index');



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

I can't migrate table into database in laravel 5.6

In laravel 5.6, when i trying to migrate table 'todos' it shows those error.Run file image

And this is table code Table code image



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

How can access property of variable if structure has lot properties

How can i I access propery of this type of data:

    $live =  =array:17 [▼
        "sensex" => {#1130 ▼
        +"code": "200"
        +"message": "Success"
        +"data": {#1131 ▼
            +"HIGH": "36551.86"
        }
      }
         "nifty_50" => {#1132 ▶}
         "nasdaq" => {#1134 ▶}

I am trying to access value of 'HIGH' property for $live variable in php. I have tired with below code but its give me error:

DD($live->sensex->data);

Error:

Trying to get property 'sensex' of non-object



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

samedi 29 septembre 2018

Why does my Laravel installation need prefixing \ backslash for facades aliases

I don't know the reason for malfunction of the following example:

Auth::user()->id 

However, just prefixing it with backslash makes it works fine:

\Auth::user()->id

This is a snippet from config/app.php

'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,

The server is Apache on Ubuntu 16.04



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

How to unit test Laravel application without ability to migrate tables because migrations are handled by another application

I've recently pointed an existing laravel project to use a new postgres DB. The new postgres DB is maintained by a Rails API application that does all the migrations for it.

My question is with this setup, what is the best way to Unit test the laravel project. Currently all the existing unit tests are broken as they all saved to the DB with the use of

use DatabaseMigrations;

The Laravel application will not be doing migrations anymore, but is still directly accesses the DB and is not currently going through the Rails api to access the data.

Should I mock out the DB requests in my unit tests?

or

Since I can still run unit tests that hit the DB if the postgres test database is already migrated with the tables ( via the rails application migrating the test DB), is there a way to empty the DB after running the unit test without the ability drop and migrate the tables? Could I use transactions somehow and rollback all the transactions I've done in a specific unit test?

Thanks



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

Laravel Save Method Isn't Updating Record

In one of my controllers, I am needing to update a specific record in another table. I have code to find the table, update the specific column, and save it. My problem is that the record is never updated. I have ensured that the column is fillable.

Here is the code that is giving me problems:

$portfolio = Portfolios::where('id', $request->portfolioID)->first();
$portfolio->totalValue = $portfolio->totalValue + $cd->currValue;
//dd($portfolio);
$portfolio->save(); 

At the die and dump that is commented out, I can compare the attributes shows the correct value and the original value was the previous value, which is still retained after the save.



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

Laravel: Efficient way to use (nolock) method

Hi guys I'm having issues when i do some selects, so the question is, whats the best way to use with nolock with query builder of laravel?



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

Images are not loading after Transferred Laravel Website on server

I have transferred website from local to web server, mean while i changed some scenarios.

1- I have changed folder structure and moved public folder files on root.

2- Image files are being uploaded into store folder while symbolic storage folder is moved on root also.

But after moving public folder files on root images not working. while uploaded images are being stored into main storage folder. but not linked with symbolic storage folder. so help me how can i attach again both storage folders.

Storage folder related code into config/filesystem is shown below:

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/pulic/images/'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_KEY'),
        'secret' => env('AWS_SECRET'),
        'region' => env('AWS_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],

],

main storage folder path is:

Root/Laravel_files/storage/app/public/images

while symbolic storage folder address is:

Root/storage/images



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

How to sync with pivot id in laravel

attributes table: id, name attribute_values: id, attribute_id, value products: id, name

How can save pivot attribute_id along with attribute_value_id and product_id using sync in attribute_value_product table.

attribute model

public function attributevalues(){
        return $this->hasMany('App\Model\AttributeValue');
    }

attribute value model

public function attributes(){
        return $this->belongsTo('App\Model\Attribute', 'attribute_id');
    }

product model

public function attributes(){
        return $this->belongsToMany('App\Model\Attribute', 'attribute_products');
    }

    public function attributeValues(){
        return $this->belongsToMany('App\Model\AttributeValue', 'attribute_value_products');
    }

product controller

$product->save();
$product->attributes()->sync($request->attribute);
$product->attributeValues()->sync($request->attribute_value);



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

Changing the default “From” field of email in laravel 5

When I send an email with my app from laravel, the receiver gets email from:

Example <hello@example.com>

How can I customize this?

I was able to customize the default Subject field as the answer posted in https://stackoverflow.com/a/52415107/5016573

I am using mailgun as mail server.



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

Larave verification email not sent

I've upgrade my laravel instance form version 5.6 to version 5.7. Now I try to use the built-in email verfication from laravel.

My problem is that i don't get a email after a successful registration. When I use the "resend" function the email arrives.

What is the problem?



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

SQlite NOT throwing exceptions for unknown columns in where clause

A little background: I am building an App on Laravel 5.6.33 (PHP 7.2 with sqlite 3).

So i have this weird case where in a test I am expecting an Exception but it never gets thrown. So I went digging and found that Laravel does not throw exceptions for invalid/non existent columns in where clause if the database driver is sqlite. The following code just returns an empty collection instead of throwing an exception.

\App\Tag::where('notAColumn', 'foo')->get();

Its weird and I checked all over the place to see if it was something wrong with my config and found nothing out of place. Debug is set to true etc. Im running this code for testing the app using an in memory sqlite database.

One other thing I noticed was that if I use whereRaw instead of where, exceptions are thrown as expected. so for example the following throws an exception.

\App\Tag::whereRaw('notAColumn = "foo"')->get();

Does anyone know why this maybe?



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

Send Mail Using Laravel Queue Job Not Working

I try to send mail on the background but it's not working.

I run php artisan queue:listen database on the terminal and hit the controller.

on my terminal shows queue in the process but mail not received.

please share the suggestion where i do mistake on my code.

.env file

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=database

Mail File

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class NewOrderSupplierMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.test');
    }
}

Job File

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Mail;
use Illuminate\Contracts\Mail\Mailer;
use App\Mail\NewOrderSupplierMail;

class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $details;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(Mailer $mailer)
    {
        $email = new NewOrderSupplierMail();
        Mail::to($this->details['email'])->send($email);
    }
}

Controller File

use Mail;
use App\Jobs\SendEmailJob;

$details['email'] = 'sumitsinghnaruka@gmail.com';
dispatch(new SendEmailJob($details));

On Terminal

php artisan queue:listen database

[2018-09-29 11:27:05][14143] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:05][14144] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:05][14145] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:05][14146] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:06][14147] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:06][14148] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:06][14149] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:06][14150] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:06][14151] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:06][14152] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:07][14153] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:07][14154] Processing: App\Jobs\SendEmailJob
[2018-09-29 11:27:07][14155] Processing: App\Jobs\SendEmailJob



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

How to show specific user data of pivot table?

I have a many to many relationships between users and meetings table and that's why I used a meeting_user pivot table. Now I can get all the meeting information with users but I have different types of users. Now I wanted to show the meeting information with the specific user, I mean If a user is logged in my system then he can only see the meeting information of his oot other meeting information. I am arranging each meeting with 2 types of user one is host and another is visitor.

elseif ($user->userType == 'visitor') {

        $id = \Auth::user()->id;
        //$meetings = Meeting::with(['visitors','hosts'])->find($id);
        //dd($meetings);
        $meetings = Meeting::with(['visitors','hosts'])->where($user->id = $id);
    }

I am confused should how can I get the meeting data of the user who is logged in?



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

Laravel default auth vs Token authentication

I start building a new app and wonder what will be the best way to implement auth - security wise.

What are the cons, pros, and differences between the Laravel make:auth and using jwt-auth.

Is Laravel's default auth will be enough?



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

drop-down selected option old value editing is in not working in laravel

I am trying to show the selected option value of drop-down and just used blew code and that's now working even I used the same trick for another table data and that is working fine. But I don't know why it's not working?

public function userEdit($id) {

    $user = User::find($id);
    $userType = User::first()->userType;
    $isActive = User::first()->isActive;
    $allRoles=Role::all();
    $role_user = $user->roles()->pluck('user_id','role_id')->toArray();

    return view('admin\userEdit',compact('user','allRoles','userType','isActive','role_user','selectedRole'));


}

<div class="form-group">
<label class="control-label col-md-3">User Type
    <span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-6">
    <div class="input-icon right">
        <i class="fa"></i>
        <select class="form-control"
            name="userType">

            <option @if(old('userType',$userType) == 'host') selected @endif>
                host
            </option>
            <option @if(old('userType',$userType) == 'visitor') selected @endif>
                visitor
            </option>
            <option @if(old('userType',$userType) == 'admin') selected @endif>
                admin
            </option>
            <option @if(old('userType',$userType) == 'operator') selected @endif>
                operator
            </option>

        </select>
    </div>
</div>

Can anyone help me to fix this that will show my old value when user will edit the data?



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

Issue with delete http method in firefox and laravel

Hi I have an issue in Laravel. I have a project in Laravel and I'm having issues in Firefox. In Chrome all is working fine. I have this admin view

@foreach ($messages as $message)
    <tr>
      <td>
      <a href="">
        
      </a>
      </td>
      <td></td>
      <td></td>
      <td></td>
      <td>
        <a class="btn btn-primary" href="">Editar</a>

        <form style="display:inline" action=" " method="post">
          {!! csrf_field() !!}
          {!! method_field('DELETE') !!}
          <button type="submit" class="btn btn-danger" name="button">Eliminar</button>
        </form>
      </td>
    </tr>

  @endforeach

I have a table with two buttons, second button is a form to delete the message. O have added method_field('DELETE')

Here is my routes.

Route::get('mensajes', 'MessagesController@index')->name('messages.index');
Route::get('mensajes/create', 'MessagesController@create')->name('messages.create');
Route::post('mensajes', 'MessagesController@store')->name('messages.store');
Route::get('mensajes/{id}', 'MessagesController@show')->name('messages.show');
Route::get('mensajes/{id}/edit', 'MessagesController@edit')->name('messages.edit');
Route::put('mensajes/{id}', 'MessagesController@update')->name('messages.update');
Route::delete('mensajes/{id}', 'MessagesController@destroy')->name('messages.destroy');

And here the MessagesController destroy method

public function destroy($id)
{
    //borro el mensaje
    //DB::table('messages')->where('id', $id)->delete();
    Message::findOrFail($id)->delete();

    //redirecciono
    return redirect()->route('messages.index');
}

In Chrome all works fine and message is deleted. But in Firefox, it redirects to /mensajes/{id} route and the message in shown. It seems in Firefox {!! method_field('DELETE') !!} is not working. Do anybody knows what I'm doing wrong?

Best regards.



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

vendredi 28 septembre 2018

How to get all records except the first 5 records after sorting based on a specific column

I have 18 records that are sorted based on specific column.

the first 5 records must be shown at first, and when click the specific button another records must be shown.

how can I do it ? I should use javascript?
it is my query...

           public function theMostImportant()
        {
// return  CategoryActivity::all()->sortByDesc("priority")->take(5);
       return  CategoryActivity::all()->sortByDesc("priority");
    }

in my view , my code is like this:

          @foreach($priorityProjectCategory as $importantCategory)

                                --}}

                                <li><a href="#" data-filter="."
                                       class="current"><sup>

                                        </sup></a></li>
                            @endforeach



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

get results from one to one relationship

**I make one to one relationship between two table. One for employees and other for their timesheet.

When i want to see the employee hours is not working ! So far i just enter hours through phpmyadmin.**

 public function up()
    {
        Schema::create('timesheets', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('starz_id');
            //starz = employee. I just name it starz

            for($i=1;$i<=31;$i++){
                $table->integer('Jan'.$i)->nullable();
            }

            $table->timestamps();
        });
    }

=============================================================================

Name @for($i=1;$iJan @endfor Total @foreach($timesheet as $one) @for($i=1;$i @endfor @endforeach

=============================the resutl=================================

Name Jan1 Jan2 Jan3 Jan4 Jan5 Jan6 Jan7 Jan8 Jan9 Jan10 Jan11 Jan12 Jan13 Jan14 Total

ali 1 2 3 4 5 6 7 8 9 10 11 12 13 14

=============================================================================

Also i need to know please what is the right way to calculate the actual time. For ex: i want latter make function that caculate the actual hours working hours spent from start time (9am) and end time(6.30pm). How can i do this by laravel ?



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

How to specify data field in JQuery AJAX form submission?

I need my HTML form data to arrive at the server via a JQuery AJAX POST request in exactly the same format as if the form had been submitted by a normal submit. I've tried using $.serialize() and $.serializeArray(), and neither gives the simple

$('#booking-form').on('submit', function(e) {
   var formdata = $(this).serialize();
   // process data and send ajax request
   console.log(formdata);

   $.ajax({
       headers: { 'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val() },
       type: 'POST',
       url: 'book',
       data: { data: formdata },
       success: function (data)
           {
           // Redirect to booking confirmation page:
           if(data.response == 'ok') window.location.replace(data.url);
           else alert('Card payment failed)
           },
       error: function (data) // Server error
           {
           console.log('Error:', data.responseText);
           }
       });

    // Prevent form submit.
    return false;
});

Backend is Laravel (5.4) but I think this is not a Laravel-specific issue. Logging a normal form submit gives:

array (
  'code' => '2ZSSAVGXAHMOOKGOC0SC',
  'ownername' => 'My Name',
  'housestreet' => '12 Any street, London',
  'city' => 'London',
  'ownerpcode' => 'ZipCode Here',
  'phone' => '1234567890'
)

That's the structure I'm after. But code above gives:

array (
  'data' => 'code=BUH1HGXDWW84SWGWSO84&ownername=My+Name&housestreet=12+Any+street%2C+London&city=London&ownerpcode=Zipcode+here&phone=1234567890')

or using $.serializeArray() gives:

array (
  'data' => 
  array (
    0 => 
    array (
      'name' => 'code',
      'value' => 'CC22DPHQ2F40G0GCKKK0',
    ),
    2 => 
    array (
      'name' => 'ownername',
      'value' => 'My Name',
    ),
    3 => 
    array (
      'name' => 'housestreet',
      'value' => '12 Any street, London',
    ),
etc.

How to get the data in the right format on the server over AJAX (using JQuery or plain JS)? I can't hand code the form fields into the data: parameter in the $.ajax call as some of them are dynamically generated on the server and some by JS on the front end, and include array fields for PHP to parse (e.g. form field name="item[0][extra][]")

Thanks



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

The result of the code is not displayed in the browser and there is no error in laravel

this is postController code

Alos I make Route

this is view code

after all of that i cannot find the error why my result doesn't display from data base

this tables should be displayed from database



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

White screen on laravel charts package

Laravel 5.6, For installing laravel charts package as per documents guideline from : Laravel Charts

I am facing white screen when trying to use docs. example as per below code:

Controller:

public function index()
{
    //
    $chart = new SampleChart;
    $chart->labels(['One', 'Two', 'Three', 'Four']);
    $chart->dataset('My dataset', 'line', [1, 2, 3, 4]);
    $chart->dataset('My dataset 2', 'line', [4, 3, 2, 1]);

    return view('sample_view', compact('chart'));
}

This is my blade code:

<head>
    <meta charset="utf-8">
    <title>Chart with VueJS</title>

</head>
<body>

    {!! $chart->container() !!}


<script src=https://cdnjs.cloudflare.com/ajax/libs/echarts/4.0.2/echarts-en.min.js charset=utf-8></script>
{!! $chart->script() !!}
</body>

Console error and code:

Uncaught ReferenceError: Chart is not defined at afrmduesqtlghwypvzkijnxoc_create (test:60) at afrmduesqtlghwypvzkijnxoc_load (test:72)

Console of Inspect element



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

Laravel migrations table is MyISAM table format

By default the laravel migrations table is using MYIsam engine. I have changed engine in config/database.php to InnoDB and all my other tables except migrations uses InnoDB



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

Ajax bind click to another button

I have a button (is anchor tag with class vote) which should be clicked to vote for an article via ajax request. After that I wanna update the votes count in my blade view (its a laravel application). The div with the class points should be updated but I dont know how to bind points on click to the ajax call? I hope you guys understand what I mean.. Maybe someone can help meout?

<a data-id="" class="btn vote "></a>

<div data-id="" class="points"></div>

$(document).on('click','.vote',function(){
 var $counter 
 var $button = $(this);
 var id = $button.data('id');
 var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({

  type:'POST',
  url:"{!! URL::to('article/vote/') !!}/" + id,
  dataType: 'JSON',
  data: {
      "_method": 'POST',
      "_token": token,
      "id": id,
  },
  success:function(data){
      $('.points').html(data.count);
      var color = data.voted ? '#bbb' : '#38c172';
      $button.css('background-color', color);
      console.log('success');
      console.log(data);
  },
  error:function(xhr){
      if (xhr.status == 401) {
        window.location.href = "{!! URL::to('login') !!}";
      } else if (xhr.status == 403) {
        window.location.href = "{!! URL::to('email/verify') !!}";
      }
  },
});
});



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

Why laravel timestamp fields are nullables?

this is not a technical question.

I'm using laravel for several projects and today I had a doubt: why Laravel timestamp fields are can be null? Is there a portability reason behind this choice or it is only useful?

What is the principle that they applied on this choice?



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

Laravel scheduler strange behavior in prod server

The scheduler is running at strange times, I have config a task to run every minute and locally runs OK, but in prod server runs like repeated at some times.

This is my Kernel.php code

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{

    protected $commands = [];


    protected function schedule(Schedule $schedule)
    {

        $schedule->call(function () {
            return true;
        })->everyMinute()->emailOutputTo('...')->thenPing('...');

    }

    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }


}

The execution output I get from the prod server:

19.06
19.07
19.08
19.09
19.10
19.11
19.12
19.13
19.16
19.16
19.16
19.17
19.18
19.21
19.21
19.21
19.22
19.23
19.25
19.25
19.26

Any ideas?



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

Laravel scope using calculated value

I have the following problem in Laravel 5.4: There´s a user table and a membership table, where a user can have many memberships, and a membership belongs to a user. The memberships are of annual duration, but a member will get an additional free day for each friend they recommend that registers on my site, thus the number of free days is constantly changing; this in turn changes the membership´s expiration date. So the question is: How to scope the active memberships for a given user, if the expiration date is a variable? I will need to do something like this:

First the expiration date in Membership.php:

This calculates the total days for each membership: Note that the friendsDays are calculated per user in User.php

public function getTotalDaysAttribute() {
        $days = $this->paidDays + $this->user->friendsDaysRemaining;
        return $days;
    }

This calculates the expiration date for each membership:

public function getExpirationDateAttribute() {
    $date = $this->startDay->addDays($this->TotalDays);
    return $date;
}

So far so good... Now, this is where I´m stuck (pseudo code):

public function scopeActive($query, $dateToCheck = Null) {
   $query->where($dateToCheck >= $expirationDate);
}

How to code this properly to get:

dump($user->membership()->active()->get());

Thanks in advance.



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

How to add custom properties to Laravel paginate json response

I have the following simple index method:

public function index()
    {
       // dd(Poll::paginate(2));
      return response()->json(Poll::paginate(2),200);
    }

The output of that method is looks like the following json object:

{
"current_page": 1,
"data": [
{
"id": 1,
"title": "I suppose?' said Alice. 'Why, you don't know.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
},
{
"id": 2,
"title": "Alice; but she knew that it seemed quite.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
}
],
"first_page_url": "http://127.0.0.1:8000/polls?page=1",
"from": 1,
"last_page": 6,
"last_page_url": "http://127.0.0.1:8000/polls?page=6",
"next_page_url": "http://127.0.0.1:8000/polls?page=2",
"path": "http://127.0.0.1:8000/polls",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 11
}

I want to add another array property after "total: 11" attribute such as:

,
"anotherData" : [
   "userId": 1,
   "userName": "john10",
   "message": "This is a message"
]

I have tried to understand how response()->json() works, so it can extract some data from LengthAwarePaginator object which it is the output of Poll::paginate(2) from this resource, but I could not able to understand how does it able to get an array from LengthAwarePaginator that holds the resultant keys in the json object?!

Edit

Notice: I have found the answer.



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

Laravel command not found on Debian

I'm trying to run laravel and keeps returning command not found I'm using the latest version of composer and laravel today. I think is laravel 5.7 and composer 1.7.2

I added export PATH=/home/myuser/.composer/vendor/bin:$PATH to the .bash_profile to .bahs_profile.

Than I ran source ~/.bash_profile

I've looked all over stackoverflow and google nothing!



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

How to put a delay between failed jobs on listeners

I need to set a delay between specific failed jobs on listeners. I know if specify the onption --delay=5 its works, but I need specific delay on a listener (not on standard job). I try put the property delay on Listener, but doesn't works.

<?php

namespace Froakie\Listeners;

use Carbon\Carbon;
use Froakie\Events\ExampleEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

/**
 * Class ExampleListener
 *
 * @package Froakie\Listeners
 * @author Miguel Borges <miguel.borges@edirectinsure.com>
 */
class ExampleListener implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * The number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 5;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 3;

    public $delay = 5;

    public $seconds;

    /**
     * Handle the event.
     *
     * @param \Froakie\Events\ExampleEvent $event
     * @throws \Exception
     */
    public function handle(ExampleEvent $event)
    {
//        $this->delay(5);
            throw new \Exception('test');
    }
}



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

Illuminate\Database\Query\Builder::labels does not exist

I have installed package : Laravel Charts Everything done as per Docs. but when i am trying to below code in controller. laravel give me error :

        $chart = new Chart;

    $chart->labels(['One', 'Two', 'Three', 'Four']);
    $chart->dataset('My dataset', 'line', [1, 2, 3, 4]);
    $chart->dataset('My dataset 2', 'line', [4, 3, 2, 1]);

error is:

Method Illuminate\Database\Query\Builder::labels does not exist.



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

How change static select on object select?

I can select data from table using for example code below

$ab = Order::where('user_id', 2);
    ->where('stock_id', 30);
    ->get();     
dd($ab);

And is ok, but i need create search condition and i would like create query like this below

$ab = new Order();
!empty($request->user_id) ? $ab->where('user_id', $request->user_id) : false;
!empty($request->stock_id) ? $ab->where('stock_id', $request->stock_id) : false;
dd($ab->get());

And not working. Could anyone give me a hint ?



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

Call to undefined method Illuminate\Support\Facades\Gate::define()

I am using Policy in Laravel 5.6

But getting this Error:

Call to undefined method Illuminate\Support\Facades\Gate::define()

How can I resolve this problem?

protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

and in boot:

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

        $gate->define('isAdmin', function ($user){
            return $user->role == 1;
        });
}



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

fzaninotto/faker Can you set random $count quantity of randomElements?

I am using this package to seed test data in my Laravel project.

For on field I am using this;

randomElements($array = array ('a','b','c'), $count = 1) // array('c')

My question is 2 parts;

a) can you make the $count value random? For example between 1-3.

b) I am using json_encode to avoid Array to string conversion but now values are being stored with ["example1", "example2"], how do I remove the [""]?

I understand storing arrays is not ideal but development has gone too far down this road.

Thanks!



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

How to sum the selected values from the radio button and pass to submit

I need the sum the values from the selected radio button and add to the submit button.

Find the code below :

 <?php foreach($configure['options']['option'] as $options)
  {
  ?>

<label class="containerRadio">
<input type="radio" class="calc" name="" value=" 
 _-- 
 " checked="checked">
 <span class="checkmark"></span>
 </label>

 <?php } ?> </div><br><br> <?php } ?><input type="text" name="sum"></button>
 <button type="submit" name="sum"><i class="fa fa-rupee" aria-hidden="true"> 
 </i> 
 </button>

Fimd below the javascript :

            <script type="text/javascript">
function calcscore(){
var score = 0;
$(".calc:checked").each(function(){
    score+=parseInt($(this).val(),10);
});
$("input[name=sum]").val(score)
}
$().ready(function(){
$(".calc").change(function(){
    calcscore()
});
});
</script>

Suggest a solution to add the value selected from the radio button to the default value given as "".



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

Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given,

i tried adding to cart an i keep getting this error Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given, called in C:\xampp\htdocs\laravelcart\app\Http\Controllers\ProductController.php

here is my code

cart.php model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cart extends Model
{
    //

    public $items = null;
    public $totalQty = 0;
    public $totalPrice = 0;

    public function _construct($oldCart)
    {
        if ($oldCart) {
            $this->items = $oldCart->items;
            $this->totalQty= $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }

    }

    public function add($item, $id)
    {
        $storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];

        if ($this->items)
        {
            if (array_key_exists($id, $this->items))
            {
                $storedItem = $this->items[$id];
            }
        }
        $storedItem['qty']++;
        $storedItem['price'] = $item->price * $storedItem['qty'];
        $this->items[$id] = $storedItem;
        $this->totalQty++;
        $this->totalPrice += $item->price;
    }
}



product controller
<?php

namespace App\Http\Controllers;

use App\Product;
use Session;
use App\Cart;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    //

    public function getIndex()
    {
        $products = Product::all();
        return view('shop.index', compact('products'));
    }

    public function getAddToCart(Request $request, $id)
    {
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        $cart->add($product, $product->id);

        $request->session()->put('cart', $cart);
        return redirect()->route('shop.index');

    }
}

my error seems to be coming from the $cart = new Cart($oldCart); pls help me...



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

How can i set condition if one column has NULL value then don't show results

Thas my controller file

public function myFriends()
        {

Logged user

$uid = Auth::user()->id;

Getting result from friendships table

            $friends1 = DB::table('friendships')
                ->leftJoin('users', 'users.id','=', 'friendships.user_requested') // whos is not loogged in but send the request
                ->where('status', 1)
                ->join('profiles', 'profiles.user_id', '=', 'friendships.requester')
                ->where('requester', $uid)
                ->get();

I have one more array friends2 i just skip that

            $friends = array_merge($friends1->toArray(), $friends2->toArray());
            return view('profile.friends', compact('friends'));

My view page

@foreach($friends as $uList)
*if in there column value has NULL then don't show follwers*

                      @if($uList->followingeach == NULL )
                       {
                            <?php echo Auth::user()->name .'You dont have follwers' ?>
                        }
                        @else
                        {
                            <?php echo Auth::user()->name .'Yes You have follwers' ?>
                        }
                        @endif

My DB columns

enter image description here



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

Select fields in Laravel Eloquent with relation

How can I select fields in a laravel eloquent object what I mean

User::select('username', 'firstname', 'lastname')->with(['periods' => function($){
   $->select('jobtitle')->orderBy('start_date', 'desc')->limit(1);
}])->get();

in may case on this query I get periods null



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

How to get the feedback of DB insert laravel

my database insert query is as follows

DB::table('job_details')
            ->insert([
                'job_id' => $jobId,
                'item_id' => $itemId,
                'type_id' => $typeId,
                'qty' => $qnty,
                'laminating' => $laminating,
                'mat_id' => $matId,
                'rates' => $rates,
                'sqft' => $sqft,
                'ups' => $ups,
                'master_qty' => $masterQnty
            ]);

and I want to get the status if the query was successful or failed. I don't want to check again to see if the query was successful



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

GET API OF INDIAN GOVERNMENT

There is a Indian Government webisite http://www.ipindia.nic.in/. This website is used to Register Trademark.On this website, they upload entire India's Business name in PDF file format.So I want to access data for http://www.ipindia.nic.in/ whichever they adds business name. I want to make an application in PHP Laravel using Curl. So please guys help me if you have knowledge of Access data of http://www.ipindia.nic.in/.



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

Process data in migration

I'm normalizing a table by removing a column and breaking it out in another table. Before the column is removed I need to create new entities based on the data from this column.

This all need to be done with one single deploy and migration command. So the flow need to be like this.

  1. Create new table user_roles
  2. Create user_role entities with data from user->role
  3. Remove column role from user table

What is the best praxis for doing this? Should I run some data processing code in the actual migration?

Is this kosher or should I just write a command that will do the data processing and then delete the column from this command. That feels a bit counter intuitive since this will not happen automatically if the application would be deployed fresh on a new server (since the column then is not removed in a migration)

Here's a mockup of what I want to do.

 public function up()
{
    Schema::create('user_roles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('role_id')->unsigned();
        $table->integer('organisation_id')->unsigned();
        $table->timestamps();

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

        $table->foreign('role_id')
            ->references('id')->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

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

    // MOCKUP CODE FOR creating user_roles
    $users = User::all();
    foreach ($users as $user) {
        $userRole = new UserRole();
        $userRole->user_id = $user->id;
        $userRole->role_id = $user->role;
        $userRole->organisation_id = $user->getOrganisation();
        $userRole->save();
    }

    Schema::table('users', function($table) {
        $table->dropColumn('role');
    });
}



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

Laravel post request doesnt give right data

My form is not updating the information when i manually change the textbox fields. When i get a confirmation email i get the wrong calculation in this example. When i process the information in my controllers it gets put correct in the database but incorrect in the email to my custommer. even though it uses the same information.

$('#two-inputs').dateRangePicker(
    {
        separator : ' tot ',
        startDate: '',
        endDate: '',
        beforeShowDay: function(date){
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [ disabled.indexOf(string) == -1 ]
        },
        getValue: function()
        {
            if ($('#date-range200').val() && $('#date-range201').val() )
                return $('#date-range200').val() + ' to ' + $('#date-range201').val();
            else
                return '';
        },
        setValue: function(s,s1,s2)
        {
            var total = 0;
            var temp_s1 = s1.split("-");
            var temp_s2 = s2.split("-");
            $('#date-range200').val(temp_s1[2] + "-" + temp_s1[1] + "-" + temp_s1[0]);
            $('#date-range201').val(temp_s2[2] + "-" + temp_s2[1] + "-" + temp_s2[0]);
            var start_date = s1;
            var s1 = s1.split('-');
            var s1 = new Date(s1[0], s1[1] - 1, s1[2]);
            var s2 = s2.split('-');
            var s2 = new Date(s2[0], s2[1] - 1, s2[2]);
            //alert(datediff(s1, s2));
            if(obj[$('#date-range200').val()] == null){
                var prijs = ;
            } else {
                var prijs = obj[$('#date-range200').val()];
            }

            var extra_kosten = ;
            total += extra_kosten;
            total += datediff(s1, s2)*prijs;

            $("#aantal_nachten").val(datediff(s1, s2));
            $("#prijs_per_nacht").val(prijs);
            $("#totaal_prijs_nachten").val(total);
            $("#prijs").html(prijs);
            $("#nachten").html(datediff(s1, s2));
            $("#prijs_nachten").html(datediff(s1, s2)*prijs);
            $("#extra_kosten").html(extra_kosten);
            $("#totaal_prijs").html(total);
            //alert(start_date);
            //alert(obj[$('#date-range200').val()]);
            $("#prijstable").slideDown( "slow");

        }
    });

Screenshot of the input fields This is the form inputs i used for this item.



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

laravel nested route with prefix and resource dosent work

I have many routes like these :

Route::resource('/dashboard/class', 'classController');
Route::get('/dashboard/class/get-by-filter', 'classController@getByFilter');
Route::get('/dashboard/class/get-by-search', 'classController@getBySearch');
...
...

Route::resource('/dashboard/orders', 'OrderController');
Route::get('/dashboard/orders/get-by-filter', 'OrderController@getByFilter');
...

now I want to write these with prefix ,group and resources but I have a problem when write like this :

Route::prefix('dashboard')->group(function()
    {

       Route::prefix('class')->group(function()
         {
            Route::get('/', 'classController');
            Route::get('/get-by-filter', 'classController@getByFilter');
            Route::get('/get-by-search', 'classController@getBySearch');
         });

       Route::prefix('orders')->group(function()
         {
            Route::get('/', 'OrderController');
            Route::get('/get-by-filter', 'OrderController@getByFilter');
            Route::get('/get-by-search', 'OrderController@getBySearch');
         });

});

why return 404 when I try to access show address like this :

example.com/dashboard/orders/4



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

Laravel - Nested Eager Loading

In this section, I read about Nested Eager Loading,

but this case is not indicated there.

Can i instead

$books = App\Book::with(['author.posts', 'author.comments', 'author.rating'])->get();

do this way?

$books = App\Book::with(['author' => function ($query) {
    $query->with(['posts', 'comments', 'rating'])
}])->get();

Can I make such a request?

$books = App\Book::with(['author' => function ($query) {
    $query->with([
        'posts' => function ($query) {
            $query->with('author');
        }, 
        'comments' => function ($query) {
            $query->with(['author'  => function ($query) {
                $query->where('created_at', '>=', now()->subDays(5));
            }]);
        }
    ]);
}])->get();



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

jeudi 27 septembre 2018

ErrorException Parse error: syntax error, unexpected '?>' (View: /var/www/project/resources/views/index/admin_list.blade.php) [duplicate]

This question already has an answer here:

larave version 5 php version 7.0 Symfony\Component\Debug\Exception\FatalThrowableError: …/storage/framework/views/78e34163befae40ef15870d6498b454130713c19.php90

<?php echo e(# if(true){}); ?>



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

Column value as index to generate 2 level collection

I am trying to get a collection which has index as column values. First level will have product_id as index and second level will have stock_date.

$data = Model::select('column1', 'product_id', 'stock_date')
                         ->where('some condition')
                         ->get();

$data = collect($data)->groupBy('product_id');

With the code above, I get the collection with product_id as the indexes.

I need the data of each product indexed by stock_date

If, for example, for product_id - 1, I have multiple records, I tried

$product_details = collect($data[1])->groupBy('stock_date');

But it does not index the records with stock_date further.

Need help to index them with stock_date.



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

Loading relations based on condition in laravel

Hy all I am a beginner in laravel.I am having trouble with loading relation based on a condition.

There is three tables picture, videos, and order.

order table contains the following fields

1.type => 0 or 1 (photo or video)

2.type_id

Order table contains the following relations

public function pictures()
{
   return $this->hasMany('App\Pictures','id', 'type_id);
}
public function videos()
{
   return $this->hasMany('App\Videos', 'id', 'type_id');
}

I want to load picture relation with order only if type equals 0 and video if the type is 1. Please help



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

return message and generate PDF Laravel

In laravel 5.6 I want to return 2 argument 1. message , 2. pdf .

Laravel Packege that i use for pdf is barryvdh/laravel-dompdf.
For message package is laracasts/flash.

        $data = $request;
        $pdf = PDF::loadView('admin.sample',compact('data'));
        $pdf->download('sample'); 

        $message = flash('Order Placed!!'); 

        return  response()->download($pdf);   



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

Call to a member function where() on string

im going to develop web with laravel framework. this is my code :

$valws = DB::table('layananpublik')->sum('value')->where('tahun',$tahun)->where('bulan',$stringbln)->where('kategori',$PilihKat);

and i get an error :

FatalErrorException in JobHarianController.php line 195: Call to a member function where() on string



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

Laravel form request class not found

I'm trying to create laravel form validation, so I created a form validation with the following code. The problem is that I'm getting an error "Class App\Http\Requests\RegisterForm does not exist" when I typehint the request in controller. Any help would be much appriciated. Thanks

RegisterForm.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterForm extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name': 'required',
            'email': 'required',
            'mobile_number': 'required',
        ];
    }
}

UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\RegisterForm;

class UserController extends Controller
{
    public function register(RegisterForm $request) {

    }

    public function login() {

    }
}

Laravel version 5.7 NGINX php7.2



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

How do I differentiate between sender and receiver in an chat app Laravel?

I am making a private(one to one) chat app in Laravel 5.7. The problem is with schema I think. If user1 is logged in and he creates a new conversation with user2. That would be created with conversation_id=1. Next time when user2 is logged in lets assume he will be finding his ID in sender column and he won't find his ID in sender_column, new conversation will be created which shouldn't be created because for creating the new conversation we have to check in sender and receiver column both.

Here is my schema

    =======User Table========
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

    =============Chat Table=============
    Schema::create('chats', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user1_id')->nullable();
        $table->foreign('user1_id')->references('id')->on('users');
        $table->unsignedInteger('user2_id')->nullable();
        $table->foreign('user2_id')->references('id')->on('users');
        $table->timestamps();
    });

    ===============Messages Table================
    Schema::create('messages', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('chat_id')->nullable();
        $table->foreign('chat_id')->references('id')->on('chats');
        $table->text('messages');
        $table->timestamps();

    });

Maybe you understand it by this.

Users                            Chats                                
id    name          chat_id    user1_id    user2_id
1     Mark             1           1           2
2     David            2           2           1
3     Henzard          3           2           3
                       4           3           2

Please suggest me a better solution.



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

Receiving HTTP data in Yii2 action with CSRF disabled

I have been trying to receive data in my Yii2 application which is been send as HTTP POST for a while now. I have tried multiple algorithms and methods but the all failed. This data is send to my application from an api. I have disabled CSRF in the controller by public $enableCsrfValidation = false; and I have set default values to be stored when this action is executed and it works. I have tried to store all the data I get from $post = Yii::$app->request->post() or $post = Yii::$app->request->get() or $post = \yii::$app->request->bodyParams. All of this methods turn to return an empty array to my action.

But It is expected that the following data structure should be returned to by action POST http://www.example2.org/notif { "status":"SUCCESS", "notif_token":"dd497bda3b250e536186fc0663f32f40", "txnid": "MP150709.1341.A00073" }

I do not know where I am getting it wrong, or what is restricting the data from reaching my controller. Any Ideas around this will be greatly appreciated



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

Laravel: Why does eager loading only keep results for last model?

If I execute the following:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9])
                    ->get();

Then I get the following result:

Illuminate\Database\Eloquent\Collection {#1104
 all: [
   App\Assignment {#1112
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#986
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#945
         all: [
           App\Record {#853
             id: 6624,
             unit_id: 6,
             process_date: "2017-09-19",
             process_hour: 14,
           },
         ],
       },
     },
   },
 ],
}

Note how the loaded unit has a record that matches the query.

Now, if I use the exact same query but add another assignment (49) to my whereIn array:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9,49])
                    ->get();

The record for assignment 49 is shown, but the record for assignment 9 does not show up anymore:

Illuminate\Database\Eloquent\Collection {#1032
 all: [
   App\Assignment {#1014
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#1283
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#1254
         all: [],
       },
     },
   },
   App\Assignment {#1061
     id: 49,
     unit_id: 29,
     start_date: "2017-02-24",
     end_date: "9999-12-31",
     unit: App\Unit {#1279
       id: 29,
       records: Illuminate\Database\Eloquent\Collection {#1131
         all: [
           App\Record {#1284
             id: 6062,
             unit_id: 29,
             process_date: "2017-03-10",
             process_hour: 13,
           },
         ],
       },
     },
   },
 ],
}

The record that matches the criteria for assignment 9 obviously exists, but for some reason it doesn't get loaded when the query finds more than one assignment with a unit/record that matches the criteria.

I tested this with more assignments as well, and in each case the record will only show up for the last assignment in the array.

What's the deal here?



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

Laravel changing config value of view_id in Analytics.php

My config/analytics.php

<?php 

return [

'view_id' => 1111111,


'cache_lifetime_in_minutes' => 60 * 24,


'cache' => [
    'store' => 'file',
  ],
];

What I want to happen is set the view_id => googleApi at my Controller.

public function showSpecificSite($site_id){

$reports = Report::whereHas('site', function($query) use($site_id) {
         $query->where('site_id', $site_id);
})->get(['email_date', 'url', 'recipient', 'report_id', 'site_id']);

$googleApi = DB::table('sites')->where('site_id', $site_id)->value('ga_id');
Config::set('view_id', $googleApi);

$siteName = Site::find($site_id)->site_name;

return view('newsite', compact('site_id', 'siteName', 'reports'));
}

I tried config:set but it didn't help me at all.

Do you have any idea or thoughts how to fix this?



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

NotFoundHttpException after deploying laravel project, why?

I have uploaded the laravel project in root in a folder called wajabatapp, and the content of the public folder I moved them to public_html folder, and I've edited the index.php to refer to the folder named wajabatapp.

When I entered the url if gives NotFoundHttpException page, I've double checked the routes and everything is fine.

enter image description here

Note: I use laravel 5.4 and PHP version 5.6

Is there any other configuration I miss?



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

In Laravels Eloquent, how do I get records with relationship?

I am trying to pull all records that have an event relationship which has an event date of today. I have the following code:

    EventStaffStation::with([
        'event' => function($query) {
            $query->where('event_date', Carbon::now()->format('d-m-Y'));
        }
    ])->where([
        'staff_id' => auth()->user()->id
    ])->has('event')->get()

This gives me a record event_staff_stations but it sets the event relationship to null. I want the record to not be returned if the relationship is null.

Basically if event_staff_station record isn't for today then I don't want it returned. I'm only interested in records with an event day of today.

Any help is appreciated.



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

save() and push() are too slow in laravel with white screen result

i have this two related table :

Users --> id | username | password | ...

Users_profiles --> id | user_id | firstname | lastname | ...

My User Eloquent is :

class User extends Authenticatable
{

    protected $fillable = ['username','password','status','type'];

    protected $hidden = [
        'password', 'remember_token',
    ];

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

My User Controller is :

public function Update($id, Request $r){
        $rules = [
            'username'  => 'unique:users,username',
            'firstname' => 'required',
            'lastname'  => 'required',
            'mobile'    => 'required',
        ];
        $validator = \Validator::make($r->all(), $rules);
        if ($validator->fails()) {
            return response()->json(['status' => 'failed', 'message' => $validator->errors()->first()]);
        } else {
            $users = User::with('profile')->where('id',$id)->first();
            $users->username = $r->username;
            $users->profile->firstname = $r->firstname;
            $users->push();
            return response()->json(['status' => 'success', 'message' => "OK"]);
        }
    }

But now when i try to update my record in first it takes long time (about 1 min) and then after update users.username and without changes any thing on users_profile table, appears white screen.

also save() method has this results again.



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

Editing user info using laravel

I've built a cms interface for the admin in my website. among other things the admin can add\edit users info using forms. when I send the edit form I keep getting this error: Column not found: 1054 Unknown column 'updated_at' in 'field list' which suggests that the DB update is trying to save all of the request indexes (which contains values of columns from other table) and not just the one I'm trying to update.

I've manage to track the problem to one line $user_role->save();. the lines above that do what their suppose to (finding thr correcct user_role and change its value).

Here is my code

Model

static public function update_user($request, $id){
        
        $image_name = '';

        if( !empty($request['profile_image']) && $request->hasFile('profile_image') && $request->file('profile_image')->isValid() ){

            $file = $request->file('profile_image');
            $image_name = date('Y.m.d.H.i.s') . '-' . $file->getClientOriginalName();
            $request->file('profile_image')->move( public_path() . '/images/profile-images/' , $image_name);
            $img = Image::make( public_path() . '/images/profile-images/' . $image_name );
            $img->resize(370, null, function ($constraint) {
                $constraint->aspectRatio();
            });
            $img->save();

        }
        $user = self::find($id);
        $user->name = $request['name'];
        $user->email = $request['email'];
        $user->phone = $request['phone'];
        if( !empty($request['password']) ){
            $user->password = bcrypt($request['password']);
        }
        if(!empty($image_name)){
            $user->profile_image = $image_name;
        }
        if( !empty($request['role_id']) ){
            $user_role = Users_role::find($id);
            $user_role->role_id = $request['role_id'];
            $user_role->save();
        }
        $user->save();
        Session::flash('sm', 'Your profile has been updated');
        Session::flash('sm-position', 'toast-top-center');
        Session::put('user_name', $request['name']);
    }

View

<div class="row">
    <div class="span9">
        <div class="content">
            <div class="module message">
                <div class="module-head">
                    <h3><b>Edit Product</b></h3>
                </div><br>
                    <div class="content">
                        <div class="module message">
                            <div class="module-body">
                                    <form action="" method="POST" novalidate="novalidate" autocomplete="off" enctype="multipart/form-data">
                                        <div class="module-body">
                                            @method('PUT')
                                            @csrf
                                            <input type="hidden" name="user_id" value="">
                                    <div class="form-group">
                                        <div class="input-group mb-3">
                                            <div class="w-100 field-input-cms">
                                                <label for="category-id" class="input-group-text h-50"><span class="text-danger">*</span><b> Permissions:</b></label>
                                                <select name="role_id" class="custom-select span-8">
                                                    <option @if ( $user->role_id == 8 ) selected="selected" @endif value="8">Admin</option>
                                                    <option @if ( $user->role_id == 2 ) selected="selected" @endif value="2">Regular</option>
                                                </select>
                                            </div>
                                            <small class="text-muted help-text">Please select one option</small><br>
                                            <span class="text-danger">&nbsp; </span>
                                        </div>
                                        <div class="w-100 field-input-cms">
                                            <label for="name" class="input-group-text h-100"><span class="text-danger">*</span><b> Name:</b></label>        
                                            <input type="text" value="" name="name" style="width:100%" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
                                        </div>
                                        <small class="text-muted help-text">Name of user</small><br>
                                        <span class="text-danger">&nbsp; </span>
                                        <div class="field-input-cms w-100">
                                            <label for="email" class="input-group-text"><span class="text-danger">*</span><b> Email:</b></label>        
                                            <input type="text" value="" name="email" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
                                        </div>
                                        <small class="text-muted text-balck help-text"> Email of user</small><br>
                                        <span class="text-danger">&nbsp; </span>
                                        <div class="field-input-cms w-100">
                                            <label for="phone" class="input-group-text"><span class="text-danger">*</span><b> Phone:</b></label>        
                                            <input type="text" value="" name="phone" size="120" class="form-control mw-100" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
                                        </div>
                                        <small class="text-muted text-balck help-text"> Phone number of user</small><br>
                                        <span class="text-danger">&nbsp; </span>
                                            <div class="input-group mb-3">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
                                                </div>
                                                <div class="custom-file">
                                                    <input type="file" name="profile_image" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
                                                    <label class="custom-file-label" name="profile_image" for="inputGroupFile01">Choose file</label>
                                                </div>
                                            </div>
                                            <small class="text-muted help-text">Image must be: jpg, jpeg, png, gif. Max: 5mb</small><br>
                                            <span class="text-danger">&nbsp; </span>
                                        </div>
                                        <div class="form-group">
                                            <img id="cms-profile-image" src="" >
                                        </div><br>
                                        <a class="btn btn-inverse" href="">Cancel</a>
                                        <input type="submit" value="Save Product" name="submit" class="btn btn-primary">
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
            </div>        
        </div> <!--/.content-->
    </div><!--/.span9-->
</div>

Image of the error gaven by laravel

enter image description here

I should mention that if I comment out this code:

        if( !empty($request['role_id']) ){
            $user_role = Users_role::find($id);
            $user_role->role_id = $request['role_id'];
            $user_role->update();
        }
all the values are saved correctly.

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