mercredi 31 octobre 2018

We were unable to decode the JSON response from the Mandrill Api mail not send

I am using the standard Code from Source mandrill-api-php/src/Mandrill.php i got error We were unable to decode the JSON response from the Mandrill API and could't send mail . so any suggestion if i got this error to resend mail or queue for failed mail to resend again? Any kind of document by mandrill on this topic please provide.

May be i got this error while their server is down else working fine.



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

Google Map Request Denied Trouble

I am trying to activate google maps on the page. I install composer API without problem. And added my server/domain IP in google API. checked and added the API key into config file. After that set the Controller and the Route which is like below.

My Route:

Route::get('/', 'PagesController@map');

Here is my Controller:

public function map()
{
    $response = \GoogleMaps::load('geocoding')
        ->setParam(['address' => 'tokyo'])
        ->get();

    return view('welcome', compact('response'));
}

And I am calling it on my view:



But I'm gettin this error?

{ "error_message" : "This API project is not authorized to use this API.", "results" : [], "status" : "REQUEST_DENIED" }

Any idea why is this happening? Thank you for your help!



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

Retrieve related models using hasManyThrough on a pivot table - Laravel 5.7

I'm trying to retrieve related models of the same type on from a pivot table.

I have 2 models, App\Models\User and App\Models\Group and a pivot model App\Pivots\GroupUser

My tables are have the following structure

users

  • id

groups

  • id

group_user

  • id
  • user_id
  • group_id

I have currently defined relationships as

// In app/Models/User.php

public function groups()
{
    return $this->belongsToMany(Group::class)->using(GroupUser::class);
}

// In app/Models/Group.php

public function users()
{
    return $this->belongsToMany(User::class)->using(GroupUser::class);
}

// In app/Pivots/GroupUser.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function group()
{
    return $this->belongsTo(Group::class);
}

I'm trying to define a relationship in my User class to access all other users that are related by being in the same group. Calling it friends. So far I've tried this:

// app/Models/User.php

public function friends()
{
    return $this->hasManyThrough(
        User::class,
        GroupUser::class,
        'user_id',
        'id'
    );
}

But it just ends up returning a collection with only the user I called the relationship from. (same as running collect($this);

I have a solution that does work but is not ideal.

// app/Models/User.php

public function friends()
{
    $friends = collect();
    foreach($this->groups as $group) {
        foreach($group->users as $user) {
            if($friends->where('id', $user->id)->count() === 0) {
                $friends->push($user);
            }
        }
    }

    return $friends;
}

Is there a way I can accomplish this using hasManyThrough or some other Eloquent function?

Thanks.



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

"Class 'Nexmo\\Laravel\\Facades\\Nexmo' not found" Error

I am trying to send an sms once a user signs up but it keep getting:

"Class 'Nexmo\\Laravel\\Facades\\Nexmo' not found"

I have this at the top of my controller file:

use Nexmo\Laravel\Facades\Nexmo;

I also have this in my config/app.php file

'Nexmo' => Nexmo\Laravel\Facades\Nexmo::class,

Im still getting an error, does anyone or has the same problem. I know its a class type error but why if I have added the right class and im using it appropriately.

Also, here is my code implementation:

Nexmo::message()->send([
    'to' => '1122334455', //not actually using this number
    'from' => 'Test',
    'text' => 'Hey, test this digit code',
    'text' => $request->user()->activation_token
]);



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

Delete or Get all the data with specific name tag in laravel

Table 1: products: id, title, publish,created_at
Table 2: tags: id,name,lang,created_at
Table 3: taggable: id,tag_id,taggable_type,taggable_id

In product model:

public function tags()
{
    return $this->morphToMany('App\Tag', 'taggable');
}

I create a new record (in tags table)

$cat = Category::find(1);
$tag = \App\Tag::firstOrCreate(['name' => 'key1']);

Now I save related data in taggables table:

$cat = Category::find(1);
$cat->tags()->save($tag);

It works.

Now I want delete all record for $cat in the taggables:

$cat->tags()->detach();

It works.

Now,in taggables table,I do not have any related data for 'key1' in tags table. So I want delete it.

The Questions:

How can I check that record (name = 'key1') in tags has not any related record in taggable and how can I delete it?



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

Problem in inserting data into many to many relationships using attach() function laravel

i have two tables (orders & products) and one pivot table (order_product). i have made many to many relationship b\w them using following code.

class Product extends Model{
 protected $fillable = ['name', 'price', 'is_iframe_product'];
  public function orders() {
      return $this->belongsToMany(Order::class);
}   }


class Order extends Model{
public $guaded = ['id'];
 protected $fillable = ['is_iframe_order','price', 'status', 'address_id', 'user_id'];
public function products () {
    return $this->belongsToMany(Product::class);
}     }

i am using following code to insert records in CheckoutController.php

 $Product = array('name' => $item['item_name'], "price" => $item['price'], "is_iframe_product" => "1");
      $saved = order()->products()->attach([$Product]);

but getting this error:

exception: "Symfony\Component\Debug\Exception\FatalThrowableError" file: "C:\wamp3\www\jewellery\jewellery\app\Http\Controllers\CheckoutController.php" line: 63 message: "Call to undefined function App\Http\Controllers\order()"



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

Laravel relation Post and categories

I have a relationship between Post Model and Group Model (belongsToMany):

class Post extends Model
{
    public function category(){
        return $this->belongsToMany('App\Category');  
}

    public function groups(){

        return $this->belongsToMany('App\Group');
    }

}

And I have a relation between categories and post ^.

so when I create a group I choose a post for it and I want to show the post category in the table.

how I can use the categories in groups?

like $group->category()

Thanks



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

I am trying to delete a record from my database using laravel but i find Sorry, the page you are looking for could not be found

This is my controller

public function index($value)
{
    $findRecord = marks::findOrFail($value);
    $findRecord->delete();
    $data['data']=DB::table('student_Registrations')->get();
return view('marks',$data);
}

this is my route

 Route::resource('deleteRecord/{value}','deleterecordController');

the record is not deleted from the database



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

Laravel FormRequest Validation: if non-required field fails validation, change the value to null and continue

I'm using Laravel 5.5 with FormRequest Validation. My current code is below. This is being used to validate the data form the request coming in.

If a nullable field fails validation in the request, I want the request to continue and make that field's value to NULL. So ,for example, if count is sent as a string instead of an integer.. I want to make the value of count NULL and continue with the request.

Is this possible using this FormRequest and if so, how?

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Response;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class FieldsCheck 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 [
            'userid' => 'required|integer',
            'custom' => 'nullable|string|max:99',
            'count' => 'nullable|integer'

        ];
    }


    protected function failedValidation(Validator $validator)
    {
        // if it fails validation, is there a way to change the failing value to null here and continue with the request?
    }

}



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

Laravel Route Always Goes to index

In my Laravel application, I store a new user via Ajax to the DB. The app always calls the index method. What's wrong?

When I remove the Route::post('/users', 'Admin\UserController@store'); route there is a 405 error. That's correct. But why doesn't it go to the store method?

Controller

<?php

class UserController extends Controller
{

    public function index()
    {
        return view('admin.user.index');
    }

    public function create()
    {
        //
    }

    public function store(UserCreateRequest $request)
    {
        $user = User::createFromRequest($request);

        return response()->json(["id" => $user->id]);
    }
}

Routes

Route::group(['prefix' => 'admin', 'as' => 'admin.', ], function () {
Route::get('/users/{user}', 'Admin\UserController@show')->name('users.show');
Route::post('/users', 'Admin\UserController@store');
Route::put('/users/{id}', 'Admin\UserController@updateFromDatatable');
Route::delete('/users/{id}', 'Admin\UserController@destroy');
Route::get('/users', 'Admin\UserController@index')->name('users.index');



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

Carbon::setLocale() not working Laravel 5.4

I'want to print the current date in spanish with Carbon with this format: Miércoles 31 de octubre 2018 but I only get Wednesday 31 October 2018 . I already used

Carbon::setLocale('es');
$fecha = Carbon::now()->format('l j F Y');

and

Carbon::setLocale(LC_TIME, 'es');
$fecha = Carbon::now()->format('l j F Y');

In config/app.php I tried with

Carbon\Carbon::setLocale('es');

I also tried es_ES, es_MX, es_US, es_MX.utf8 but it keeps returning the date on english. I am working on linux and I already added the locales I need.

Does anyone know how to solve this?

Thanks!



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

Trying to get property of non-object on laravel with axios

i have a little problem here and wish your help.

axios.get('/api/NewOrder',{params: {shippingInfo: this.Costumer,shipping_date: this.shipping_date,orderIteams:this.orderIteams,payments:this.payments,ordertotal:this.ordertotal,totalrecieved:this.totalrecieved}}).then(response => {
    alert(response.data);
    });

when calling api with axios i get this error "message": "Trying to get property of non-object", this is my function:

    public function store(Request $request)
{
  $neworder=new Order;
  $neworder->operatorId=auth()->guard('admin-web')->user()->id;
  $neworder->outletId= auth()->guard('admin-web')->user()->outletid;
  $neworder->shippingInfo=$request->query('shippingInfo');
  $neworder->shipping_date=$request->query('shipping_date');
  $neworder->status="en attente";
  $neworder->order_total=$request->query('ordertotal');
  $totalrecieved=$request->query('$totalrecieved');
  if ($totalrecieved < $neworder->order_total) {
    $neworder->paymentStatus="payement partial";
  }else {
    $neworder->paymentStatus="payee";
  }
  $neworder->save();
  $neworder->number = date("Y").$neworder->outletId.$neworder->operatorId.$neworder->id;
  $neworder->save();


  return response()->json($neworder);
}

thanks in advance



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

Laravel's contains() helper on Collection of associative arrays, searching with multiple arguments

I have this collection of precise GIS coordinates and I'm trying to find location matches by passing through both a lat and long using laravel's contains helper. Sample of collection as $points:

Polygon {#16091
  #points: array:103 [
    0 => Point {#719
      +x: -93.299203918246
      +y: 44.914451664177
    }
    1 => Point {#729
      +x: -93.299203946751
      +y: 44.914492803531
    }
    2 => Point {#737
      +x: -93.299203993418
      +y: 44.914561369423
    }
    3 => Point {#738
      +x: -93.299204049158
      +y: 44.914643647233
    }
  ]
}

My check is if ($points->contains($lng, $lat)) { // do something }. I'm not getting any matches, so just curious if I can even use contains() in this context? I know it works with a simpler collection. I tried hard-coding what would definitely be exact matches (pulled from the data set I am searching through) and it still returns false. Another issue I have, which I haven't even begun to address is that the coordinates that are coming from one query that sets $lat and $lng have 6 decimals (-93.208572) and the GIS data I'm searching through has coordinates with 12 decimals (44.174837264857). My understanding is that contains would still find matches, but I suppose I'll cross that bridge when I get there... I also tried to split the check up with key / value pairs:

$lngCheck = $points->contains('x', $lng);
$latCheck = $points->contains('y', $lat);

and then checking if they are both true for a match. I'm still always getting false.



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

Why did not Laravel 5.6 active menu item highlight using request?

working with laravel 5.6 and develop sidemenu bar with bootstarp. I am using request to highlight current menu items here. but it is not highlight when it is in current menu.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
 .nav-sidebar li.active{
  /*your css code here*/
 }
</style>
<li class="">
<a href="{!! route('products.index') !!}"><span>Products</span></a>
</li>
<li class="">
<a href="{!! route('tags.index') !!}"><span>Tags</span></a>
</li>
<li class="">
<a href="{!! route('items.index') !!}"><span>Items</span></a>
</li>
<script>

   $('.nav-sidebar').on('click','li', function(){
    $(this).addClass('active').siblings().removeClass('active');
  });
</script>



from Newest questions tagged laravel-5 - Stack Overflow https://stackoverflow.com/questions/53087058/why-did-not-laravel-5-6-active-menu-item-highlight-using-request
via IFTTT

Eloquent many-to-many get data

So guys, i'm starting studying laravel, but currently I'm stuck in a problem which I cannot find any solution... I've found some related solutions but after tryed none solved my problem, so it'is:

I'm in step of creating a blog, so I have posts, tags, and categories. A post belongs to just one category, and categories can belongs to many posts, from here... OK! Now, posts belongs to many tags, as tags belong to many posts... Problem!

I have my pivot table, and everything is running ok, the real problem is when I need to retrieve data from this pivot table, I cannot figure out how it should work.

What I'm trying to do is basically the user can only delete a tag if there's no posts associated to it.

Post Model

public function tags()
{
    return $this->belongsToMany('App\Tag');
}

Tag Model

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

Tag Controller (Delete Method)

public function delete($id)
{
    // Get tag by ID
    $tag = Tag::find($id);
    $tag_name = $tag->tag;

    /** Try to check data */
    if($tag->posts->count() > 0) {
        Session::flash('error', 'There is some associated posts to "' . $tag_name . '", delete them before.');
    } else {
        Session::flash('success', 'Tag "' . $tag_name . '" was deleted successfully.');
        //$tag->delete();
    }

    return redirect()->back();
}

I've tried

$tag->posts()->get()
$tag->posts->get()
Tag::find(1)->posts->get()
Tag::where('id', [1])->get()

Some other combinations, every single one return an Logic Exception or a Fatal error...

App\Tag::posts must return a relationship instance

View Button (Passing the ID)

<a href="" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i> Delete</a>

Route in web.php

Route::get('/tags/delete/{id}', 'TagsController@delete')->name('tags.delete');

I'm struggling in retrieve data from many-to-many data for a long time, it starts to getting very stressful.



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

Refer to a value just set in array within foreach loop

We've got a foreach loop that one of our console commands, it builds an array to be put in the database after being turned to Json.

In order to get one of the specific values, we'd like to reference two of the OTHER values that have been pulled in the loop

Below is the loop, the 'conversionRate' valus is what we're trying to get, from the result of the 'sales' and 'quotes' queries. I have no idea how to call those while still inside the loop.

 foreach ($users as $user) {
            $todaysCcActionsArray[] = [
                'name' => DB::Table('sw_users')->where('EmailAddress', $user)->value('FirstName'),

                'code' => $user,

                'sales' => Order::where('Status', 'BOOKING')
                ->whereNotIn('Product', ['commercial_insurance', 'home_insurance'])
                ->where('MasterOrderNumber', 0)
                ->whereNull('OriginalOrderNumber')
                ->where('CallCentreID', '!=', $user)
                ->whereDate('OrderDate', '=', date('Y-m-d'))->count(),

                'quotes' => Order::where('Status', 'QUOTE')
                ->whereNotIn('Product', ['commercial_insurance', 'home_insurance'])
                ->where('MasterOrderNumber', 0)
                ->whereNull('OriginalOrderNumber')
                ->where('CallCentreID', '!=', $user)
                ->whereDate('OrderDate', '=', date('Y-m-d'))->count(),

                'conversionRate' => 'sales' / 'quotes' * 100
            ];
        }



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

Query with circular relationship in Laravel 5.6

I have the following tables:

  1. Users;
  2. Companies;
  3. Employees.

I'm trying to bring all the employees of a company. In SQL it's pretty easy:

SELECT c.name, eu.name FROM users u
    JOIN companies c ON c.user_id = u.id
    JOIN employees e ON e.company_id = c.id
    JOIN users eu ON eu.id = e.user_id
 WHERE u.id = 2

But in Laravel I have tried everything and can not get this listing (company name + employee name) correctly.

Here are the frustrated attempts:

  1. In this I tried to get all the companies the user logged in to then list all the employees.

    $companies = Auth::user()->with('companies')->with('employee')->where('id', '=', Auth::user()->id)->get(); 
    
    
  2. Here I started with the Employee model.

    $employees = Employee::with('company')->with('user')->where('user_id', Auth::user()->id)->paginate(30); 
    
    

As the platform is multi user, it is interesting to remember that:

  1. A User has N Companies;
  2. A Company has N Employees;
  3. And an Employee belongs to ONE User.

Hence comes the circular structure of the tables.

enter image description here

Thank you.



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

Consulta com relacionamento circular no Laravel 5.6

Olá! Tenho as seguintes tabelas:

  1. Usuários;
  2. Empresas;
  3. Funcionários.

Estou tentando trazer todos os funcionários de uma empresa. No SQL é bem fácil:

SELECT c.name, eu.name FROM users u
    JOIN companies c ON c.user_id = u.id
    JOIN employees e ON e.company_id = c.id
    JOIN users eu ON eu.id = e.user_id
 WHERE u.id = 2

Porém no Laravel já tentei de tudo e não consigo obter essa listagem (nome da empresa + nome do funcionário) corretamente.

Seguem as tentativas frustadas:

  1. Nessa eu tentei obter todas as empresas do usuário logado para em seguida listar todos os funcionários.

    $companies = Auth::user()->with('companies')->with('employee')->where('id', '=', Auth::user()->id)->get();
    
    
  2. Nessa eu parti do modelo Funcionário.

    $employees = Employee::with('company')->with('user')->where('user_id', Auth::user()->id)->paginate(30);
    
    

Como a plataforma é multi usuário, é interessante lembrar que:

  1. Um Usuário possui N Empresas;
  2. Uma Empresa possui N Funcionários;
  3. E um Funcionário pertence a UM Usuário.

Dai que vem a estrutura circular das tabelas.

enter image description here



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

Laravel morphedByMany return all records by where condition and count

Table 1: products: id, title, publish,created_at
Table 2: tags: id,name,created_at
Table 3: taggable: id,tag_id,taggable_type,taggable_id

I want get all district tags with count order by name.

I want it return an array like this:

[
  ['name1'=>'value1','count'=>3],
  ['name2'=>'value2','count'=>3]
]

I try do it by this:

$tags = \App\Tag::distinct()->where( function( $query ){
                   $query->whereHas('products', function ( $subquery ){
                       $subquery->where('publish', 1 );
                   })->get()->toarray();
                 })->withCount('products')->get()->toarray();

but it return all (product) tags and all products_count values is 1 like this/:

 [...],
 [▼
    "id" => 75
    "name" => "test1"
    "created_at" => "2018-10-30 18:49:51"
    "products_count" => 1
  ],
  [...]
  ...



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

Laravel relationtable with many to many

Im stuck on how to connect my users with other tables in a clean way. I've tried to work with laravel polymorphic table handling without success. This is what my tables look like, ( ignore the plural use of equipment and armor, will change later).

A user will have many equipments which points to one weapon or armor.

:: users ::
id
name

:: equipments ::
id
user_id
equipmentable_id
equipmentable_type

:: weapons ::
id
name

:: armors ::
id
name

What i would like to do is to get weapons and armors of users

$user->weapons ( Should return all weapons )
$user->armors ( Should return all armors )

This is my current attempt using larvel polymorphic tables

UserModel:

class User extends Authenticatable
{
    public function equipments()
    {
      return $this->hasMany(Equipment::class);
    }
}

EquipmentModel:

class Equipment extends Model
{
    public function equipments()
   {
     return $this->morphTo();
   }

   public function weapons()
   {
     return $this->equipments()->where('equipmentable_id', 'App\Weapon');
   }

   public function armors()
   {
     return $this->equipments()->where('equipmentable_type', 'App\Armor');
   }

}



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

Laravel Artisan _ command restarts itself AND stop after twenty minutes

I have a question about the "command" of the Laravel artisan.

When I execute my command (massive adding data to a database with long processing processes), it stops after about twenty minutes without being finished.

Moreover, after about twenty insertions, the command restarts itself without being finished and restarts the process of adding data (it is variable, sometimes after 15 records).

To be clear, when executing the command, I don't do a cron like "->everyminute()'.

Do you have an idea to solve this problem? Is it a memory, timeout, cron or synchronicity problem ?

Thank you to you Have a good day



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

I already enter the city and location in DB in Laravel, How I will display Location in my dropdown

Please help me to get the location from database, because i have already insert city and location in my DB. but I want to show location in drop-down by cityid. Please help me to find this solution. I want this in Laravel.



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

Laravel pagination without style

Below is my code: ` @foreach($posts as $post)

                        <tr>
                            <th></th>                            
                            <td></td>
                            <td> </td>
                            <td></td>
                            <td>
                                <a href="" class="btn btn-default btn-sm">View</a>
                                <a href="" class="btn btn-delete btn-sm">Edit</a>                                  
                            </td>
                        </tr>

                    @endforeach
                </tbody>
            </table>

            <div class="text-center">
                
            </div>`

And below is the code in controller:

public function index()
{
    $posts = Post::orderBy('id', 'desc')->paginate(5);

    return view('posts.index')->withPosts($posts);
}

In spite of this, i do not get proper styling! Bootstrap styles not applied. See the image.



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

"General error: 1366 Incorrect integer value" even though I have set validation to nullable

I get this error: enter image description here

When I am trying to create and I am not filling the input for fixed_quantity

This is my store in my Controller(I have set fixed_quantity to nullable so it should be fine right?):

 $this->validate($request, [
        'name'                      => 'required',
        'description'               => 'required',
        'fixed_quantity'            => 'nullable',
        'max_increments'            => 'required|numeric|min:0',
    ]);

    DB::transaction(function () use ($request, $store, $variant) {

        $subscription_plan = new SubscriptionPlan([
            'store_id'                  => $store->uuid,
            'variant_id'                => $variant->uuid,
            'name'                      => $request->input('name'),
            'description'               => $request->input('description'),
            'max_increments'            => $request->input('max_increments'),
        ]);

        $subscription_plan->fixed_quantity = $request->input('fixed_quantity');

        $subscription_plan->save();

This is what is on my blade:

<div class="form-group">
    <label for="fixed_quantity">Quantity</label>
    <input class="form-control" type="number" id="fixed_quantity" name="fixed_quantity" value=""" placeholder="0">
</div>



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

How to find the name of a unique index? MySQL

I have something like this. I want to remove the unique index on columns: long_col_name and some_other_id. As both the table name and the columns names are quite long and all three have underscores in them, how do I remove this unique index?

mysql> SHOW INDEXES FROM long_table_name;
+--------------------------+------------+----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table                    | Non_unique | Key_name | Seq_in_index | Column_name    | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------------------------+------------+----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| long_table_name          |          0 | PRIMARY  |            1 | id             | A         |          32 |     NULL | NULL   |      | BTREE      |         |               |
| long_table_name          |          0 | unique   |            1 | long_col_name  | A         |          32 |     NULL | NULL   |      | BTREE      |         |               |
| long_table_name          |          0 | unique   |            2 | some_other_id  | A         |          32 |     NULL | NULL   |      | BTREE      |         |               |
+--------------------------+------------+----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
3 rows in set (0.00 sec)

I'm using Laravel but I just need something that will work in either Laravel or MySQL.

Is the unique key called this... long_table_name_long_col_name_some_other_id_unique?

How would I remove the index like this in mysql?

ALTER TABLE long_table_name DROP ???;

Or using Laravel..

        if (Schema::hasColumn('long_table_name', 'long_col_name')) {
            Schema::table('long_table_name', function (Blueprint $table) {
                $table->dropUnique('long_table_name_long_col_name_some_other_id_unique');
            });
        }

Gives the error...

SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'long_table_name_long_col_name_some_other_id_unique'; check that column/key exists (SQL: alter table `long_table_name` d  
rop index `long_table_name_long_col_name_some_other_id_unique`)  

I get the same error when I do...

$table->dropUnique(['long_col_name','some_other_id']);

Any ideas?



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

Canonical Issue in Laravel with ID and Slug use

Looking for canonical issue in my site is I can get the right canonical url like

http://www.example.com/quotes/123/this_is_it

but if someone changes the 123 to 158 it still shows the content of 123. I think it get the content with the slug i.e. this_is_it.

What I want is to get a 404 or a redirect to actual page if someone tries to change any one of either {id} or {slug}

I got my route as

Route::get('/quotes/{id}/{slug}','QuotesController@quoteShow');

and controller as

public function quoteShow($id,$slug)
{
    $quotes= DB::table('quotes')->where('id', $id)->get();
    foreach ($quotes as $data) {
        $id= $data->id;
        $author_id= $data->author_id;
        $quote= $data->quote;
        $status= $data->status;            
    }

    $author= DB::table('authors_list')->where('id', $author_id)->get();
    return view('pages.quote',  ['author' => $author, 'quotes'=>$quotes]);
    }



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

laravel update relationship data manually in controller before forwarding to view(blade)

I have changed data got from relationship of eloquent and now want to update relationship data with my custom data. Any idea how to do that? e.g.

$data = $model->perticularRelaion;
$data->operations; //to update data
now want to do something like this
$model->perticulaRelation = $data;

so when retrieve data in blade it show my updated relationship data.



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

Laravel Socialite 403 Forbidden error when redirect back

I am trying to log in with Google+ API in my website using Socialite package. but it is not working as expected. I am developing a website in Laravel. The API is working fine returning all data using JS but when I am trying to do this using Socialite, It showing 403 Forbidden Error page when redirecting back.

My Route:

Route::get('auth/{provider}', 'Auth\AuthController@redirectToProvider');
Route::get('auth/{provider}/callback', 'Auth\AuthController@handleProviderCallback');

Redirect Method:

public function redirectToProvider($provider)
{
    return Socialite::driver($provider)->stateless()->redirect();
}

Callback Method:

public function handleProviderCallbackd($provider)
{
    $user = Socialite::driver($provider)->stateless()->user();

    $authUser = $this->findOrCreateUser($user, $provider);

    Auth::login($authUser, true);
    return redirect($this->redirectTo);
}

I have tried to use stateless() method to avoid the error but it is not working.

Note: When it redirect back the URL has scope parameter, if I remove that parameter then it works fine.



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

Guzzle http request to nodejs server connection refuse

My Laravel PHP code is running inside vagrant homestead. Here is my PHP function that is going to send the http request to nodejs server.

private function sendcampaign($data) 
    {

        $client = new Client();

        $res = $client->request('POST', 'http://127.0.0.1:8080/sendcampaign', ['json' => $data]);

        $response = $res->getBody();

        if($res->getStatusCode() == 200) 
        {

            Log::info($response);

        } else {

            Log::error($response);

        }
    }

My NodeJS server is running independently. I run it using this command nmp start. Here is the code to my nodejs server that is accepting the request

app.post("/sendcampaign", function(request, response) {
  if (request.body) {

    var campaign = JSON.stringify(request.body);

    response.status(200);
    response.send({
      status: "success",
      message: "Campaign sent successfully."
    });

  } else {
    response.status(404);
    response.send({ status: "error", message: "Campaign failed." });
  }

  return;
});

However when I run it, I always getting an error

cURL error 7: Failed to connect to 127.0.0.1 port 8080: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

But I already tried it in Postman the response is

{"status":"success","message":"Campaign sent successfully."}

I don't know what's the error on my PHP code using GuzzleHttp. Maybe I need to add some header options? What header options should I add? Can you help me?



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

Why only first controller is working in Laravel

I have 2 Controllers in Laravel as

Route::get('/books/{slug}', 'BooksController@slugShow');
Route::get('/books/{alphabet}', 'BooksController@showByAlphabet');

Both controllers are working fine when using only one but when I put them both in Routs file only the first one works.

slug urls are like

https://www.example.com/books/once_upon_a_time

and Alphabets urls are list of books starting with an alphabet

https://www.example.com/books/a

How Can I make them both work and I also want urls of alphabets to not work if there are more than a single character in the url like

https://www.example.com/books/aa
or
https://www.example.com/books/once



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

Laravel Eloquent triple Relationship

I am stuck in situation where I need relation between 3 different tables. My tables are companies, products and Roles. Companies can assign multiple Roles to multiple products. The problem is Companies do not have any relationship with products. Products are added through admin.

Currently I have made a table company_product_role with structure company_id, product_id and role_id, the problem is how to make eloquent relation for insertion and retrieval. Either I am doing it correct or there is simple solution for it?

Any help will be appreciated.



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

Laravel - Faking route in PHPUnit

I've been writing some tests in PHPUnit (version 7.4.3), but in some files in my project (a Laravel 5.7.12 JSON API) I need to use the route (/users/123/posts/456), but when PHPUnit calls the route, request()->getPathInfo() returns "".

Is there some way to fake this, or fill it with the correct data?

I am calling the route using $this->getJson(route('users.index')); in the test class.



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

Laravel queue (regardless of driver) processes a job only after the next is queued

Yesterday I noticed this really weird Laravel queue behavior. Please help me understand what is going on.

$ laravel new test
$ cd test
$ php artisan make:job TestQueue

Paste the following into the TestQueue class. Nothing fancy, really:

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class TestQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($id)
    {
        Log::info('Creating ' . $id);
        $this->id = $id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info('Running ' . $this->id);
    }
}

Now, regardless of the QUEUE_CONNECTION env var (redis, beanstalkd, even sync!), I get the following behavior:

Please note I have php artisan queue:work running in a separate terminal.

$ php artisan tinker

>>> App\Jobs\TestQueue::dispatch(1)

logs:

[2018-10-30 22:38:01] local.INFO: Creating 1

>>> App\Jobs\TestQueue::dispatch(2)

logs:

[2018-10-30 22:38:04] local.INFO: Creating 2
[2018-10-30 22:38:06] local.INFO: Running 1

>>> App\Jobs\TestQueue::dispatch(3)

logs:

[2018-10-30 22:38:22] local.INFO: Creating 3
[2018-10-30 22:38:24] local.INFO: Running 2

I believe not only the queue, regardless of the driver, should pick up the first job and process it whenever queue is ready, but the sync driver should process every queued job immediately (calling its handle() method).

I feel like someone's trying to prove me 1+1=3 and I just can't see what I'm doing wrong. I'm sure this is not a bug in the framework, because the internet would be raving about it, and it is not.

Thank you for your time.

Laravel Framework 5.7.12

Edit: local environment, config is not cached



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

I want to add Search Bar in my CRUD Operations in Laravel5, how can i do that?

I am Laravel Beginner and i have created CRUD operations in laravel and now i want to add search bar in my index page where all the data is displaying so just tell me the steps and query of searching the data from database



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

Laravel 5.7 validation rules

When I submit a form, this is what I do to validate my fields:

         $this->validate( $request, [
            'name'                 => __( 'required|max:255|unique:templates,name,NULL,id,company_id,:company_id', [
                'company_id' => $request->input( 'companies' )
            ] ),
            'modules'              => 'required|numeric',
            'companies'            => 'required|numeric',
            'start_date'           => 'required_with:limited_availability|date|before:end_date',
            'end_date'             => 'required_with:limited_availability|date|after:start_date',
            'indesign_location'    => __( 'required|file|mimetypes:application/zip|max::max_upload_size', [
                'max_upload_size' => config( 'file.max_size' )
            ] )
        ] );

What I want to achieve: The fields start_date and end_date should only be required (and therefore be validated) when the field limited_availability is present.

What happens now is that I don't get the message that the field is required, but I do get an error message on both date fields that the specified date is invalid.

How can I fix this problem?



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

Validate Json - Laravel

Hello I'm new in laravel and have some strange situation:

in laravel api.php I have route

Route::get('/blog', function() {
    $url_query_string = "format=json";
    $request_url = 'https://www.squarespace.com/templates/?' . $url_query_string;
    $ch = curl_init($request_url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_TIMEOUT, 20);
          curl_setopt($ch, CURLOPT_USERAGENT, 'H.H\'s PHP CURL script');
    $response_body = curl_exec($ch);
    curl_close($ch);


    $res = json_decode($response_body,true);
    echo json_encode($res);
});

so it is working but not gives me validated json it is not correct look at picture

enter image description here

not sure where is a problem?



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

How to convert MySqli Loop Code Laravel controller

I want to work on a while loop in a foreach loop but I can't convert it to Laravel controller system. Please help.

foreach (range('a', 'z') as $i) 
{
echo $i = strtolower($i); 
$sql = "SELECT * FROM `list` Where name like '$i%' Limit 30";
$result = mysqli_query($con, $sql);
echo"<hr>
    <h3>Name Starting with ".strtoupper($i)."</h3>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
    $id = $row['id'];
    $name = $row['name'];
    echo "<li><a href=\"name/".$row['id']."\">".$row['name']."</a></li>";
}
echo "<li><a href=\"name/".$i."\">More</a></li>";
echo"</ul>";
}

The code in Laravel that I have is

foreach (range('a', 'z') as $i) 
    {
        $list = DB::table('list')->where('name', 'LIKE', $i.'%')->limit(30)->get();            
        return view('pages.all', ['list' => $list]);            
    }

This code only Gives data for names starting with alphabet "a" but won't proceeds with the rest of the characters.



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

mardi 30 octobre 2018

mike42/escpos-php not working on internet web server

I've Got a problem with mike42/escpos-php.i add this package to my laravel project it working correctly on localhost. but after i host my project on the internet its not working, please help me to solve this,



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

How to fix Doctrine\\DBAL\\Driver\\PDOException error in docker with laravel 5 app

I have problem with running my laravel 5.5/postgres app in docker asp I see error in my logs

could not find driver {"exception":"[object] (Doctrine\\DBAL\\Driver\\PDOException

usually to fix this error I have to run in console of my ubuntu :

composer require doctrine/dbal

I have in file docker-compose.yml :

...
    lprods_composer:
        image: composer:1.6
        container_name: lprods_composer_container
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        working_dir: ${APP_PTH_CONTAINER}
        command: composer install  --ignore-platform-reqs

Which way is to salve it? I suppose I have to set this option in my docker-compose.yml file ?

Thanks!



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

how to show questions options together in laravel after explode?

 public function index()
{
    $subCategory = Category::where('status' , 0)->where('parent_id' , '!=' , 0)->get();
    $categories = Category::where(['status' => 0 , 'parent_id' => 0])->get();
    $questions = Question::join('question_options' , 'questions.id','=','question_options.question_id')->where('status' , 0)->get(['questions.*' , 'question_options.options' ]);

    return view('questions')->with(['categories' => $categories , 'subCategory' => $subCategory , 'questions' => $questions]);
}



public function addQuestion(Request $request)
{
    $categoryName = $request->input('category_id');
    $subCategoryName = $request->input('sub_category_id');
    $questionDetail = $request->input('question_detail');
    $questionOptions = $request->input('options');
    $questionAnswer = $request->input('answer');
    $questionType = $request->input('type');
    $validation = Validator::make($request->all(), [
        'category_id' => 'required|max:100',
        'question_detail' => 'required|max:100',
        'options' => 'required|max:100',
        'answer' => 'required|max:100',
        'type' => 'required|max:100',
    ]);
    if ($validation->fails()) {
        return redirect()->back()->with('$error', $validation->errors()->first());
    } else {

        $location = 'images/question_images';
        $questionImg = "";
        $getImage = (new customSlim())->getImages();
        if(count($getImage) > 0){
            $questionImage = $getImage[0];
            $questionImgSave = (new customSlim)->saveFile($questionImage['output']['data'], $questionImage['input']['name'], $location);
            $questionImg = $questionImgSave['name'];
        }

        $question = new Question();
        $question->category_id = $categoryName;
        $question->question_detail = $questionDetail;
        $question->image = ('images/question_images/'. $questionImg);
        $question->option_id = $questionAnswer;
        $question->type = $questionType;
        $saveQuestion = $question->save();
        if($saveQuestion){

            $QuestionoptionsArray = explode(',', $questionOptions);
            foreach($QuestionoptionsArray as $option){
                $Questionoptions = new QuestionOption();
                $Questionoptions->question_id = $question->id;
                $Questionoptions->options = $option;
                $Questionoptions->save();
            }
        }
    }
    if ($saveQuestion) {
        return redirect()->back()->with(Session::flash('alert-success', 'Question Added Successfully!'));
    } else {
        return redirect()->back()->with(Session::flash('alert-danger', 'Failed to Add Question'));
    }
}

sample

The question is how i can show question options together in one line. like (six,eight,five,nine). i have two database one for question and other is for question options where i'm saving question option with explode() along question id. how can i show this?



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

how to delete by owner and read to anyone on laravel nginx login

When I register two users on laravel (on MySQL DB user table) upload a file separate by two users. On Ubuntu Cmd $ls -alh. The file owner all shows www-data:www-data no matter who's the user upload. I has already set the folder to 755 and the file to 644.
So how can I identify which user has the right to delete the file he uploaded and prevent the other user to delete the file because files all show the same owner on Linux system? Purpose: 1.everyone can read the file in the folder 2.register users can upload file to the folder 3.register user can only delete the file he upload

What's the confused point I got ? Can the loginer can have the file ownership and can be restrict by the 644 permission?



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

Laravel relation with types

I have tried to find the best solution for my problem without getting exactly what i want.

I have 4 tables now, the structure looks like this.

:: Users ::
id
name
email
------

:: user_equipment ::
id
user_id
equipment_id
equipment_type

:: weapons ::
id
name
price

:: armor ::
id
name
price

My goal is to be able to use my relations like this:

$user->equipment
$user->equipment->weapons
$user->equipment->armor

Here is what i have right now:

User Model:

class UserEquipment extends Model
{    
  public function equipment()
  {
    return $this->hasOne(UserEquipment::class);
  }
}

UserEquipment Model:

class UserEquipment extends Model
{
   public function weapons()
   {
     return $this->hasMany(Weapon::class);
   }
}



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

laravel: avoid miscellaneous parameters in get method

For example I have this url:

http://127.0.0.1/public?valid=test1&invalid=test2

So I send 2 parameters to a related function in its controller:

       $input = $request->all();
       $validator = Validator::make($input, [
         'valid' => 'nullable|string',
       ]);

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

I expect this url works:

http://127.0.0.1/public?valid=test1

But for this: http://127.0.0.1/public?invalid=test2

I do not want this url works because I do not define invalid parameter in Validator (The route accepted that URL):

Dose laravel support to refuse miscellaneous parameters?

The laravel website has that bug too

https://laravel.com/?asd=asd

My solution:

$input = $request->all();
$valid = ['valid'];
foreach($input as $key => $val)
{
   if(!in_array($key,$valid)) abort(404);
}



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

Laravel WorkflowSubscriber class that conditionally calls guard methods based on the current transition calling incorrect methods

I have an unnecessarily perplexing situation here. I'm simply trying to create a method that checks an events transition, creates a $guardMethod variable that will look something like guardToSomePlace and then if that method exists, call it. Here is the code for that concept:

<?php

namespace App\Listeners;

use App\Models\BugTypes\Bug;
use Symfony\Component\Workflow\Event\GuardEvent;

class BugWorkflowSubscriber
{
    /**
     * Handle workflow guard events.
     *
     * @param \Symfony\Component\Workflow\Event\GuardEvent $event
     */
    public function onGuard(GuardEvent $event)
    {
        $transition = $event->getTransition();
        $guardMethod = 'guard' . studly_case($transition->getName());

        if (method_exists($this, $guardMethod)) {
            $this->$guardMethod($event);
        }
    }

    /**
     * Guards the to_on_hold transition
     *
     * @param \Symfony\Workflow\Event\GuardEvent $event
     *
     * @return void
     */
    private function guardToOnHold(GuardEvent $event)
    {
        dd('why is it getting here for other transitions?');
    }

    /**
     * Register the listeners for the subscriber.
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'workflow.bug.guard',
            'App\Listeners\BugWorkflowSubscriber@onGuard'
        );

        $events->listen(
            'workflow.bug.entered.*',
            'App\Listeners\Workflow\Bug\OnEntered'
        );
    }
}

It is calling the guardToOnHold method for multiple transitions, despite the fact that I can dd $event->getTransition() and it is the correct transition and if I dd method_exists($this, $guardMethod) it is false for any/all methods besides guardToOnHold, as that's the only one that would exist after I create the $guardMethod variable. If I dd method_exists($this, $guardMethod) before the if statement it is false, but dd-ing it inside the if statement with the same event/transition gets into the if statement and dd's true. This is Laravel 5.7 using the Brexis/Laravel Symfony Workflow package. The transition on the event is always what I expect it to be. $event->getTransition() always returns one Transition Object with the correct name, froms and tos.



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

laravel -how to logout session after checking remember me on a custom guard?

I created a custom guard in laravel the problem i am having with the custom guard is that when i check the remember me function on the login page, i can login in but when i want to sign out i can not terminate the session. I know that the problem is in the logout functionality but not sure how to fix the issue. I tried to copy the logout function in the authenticatesuser.php but still wasn't able to terminate the session and log out.

logincontroller

<?php

namespace App\Http\Controllers\CustomerAuth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;

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

    use AuthenticatesUsers;

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

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

    protected function guard()
    {
        return Auth()->guard('customer');
    }

    public function logoutcustomer()
    {
    $customer =  Auth::guard($customer)->logout();
        $customer->session()->invalidate();
        return redirect('/');
    }



    public function showLoginForm()
    {
        if (Auth::user() || Auth::guard('customer')->user()) {
            return redirect('/');
        } else {
            return view('customer-auth.login');
        }
    }
}


AuthenticatesUser.php

public function logout(Request $request)
{
    $this->guard()->logout();

    $request->session()->invalidate();

    return redirect('/');
}



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

Illegal offset type in isset or empty in laravel file auth manager.php

protected function resolve($name) { $config = $this->getConfig($name);

    if (is_null($config)) {
        throw new InvalidArgumentException("Auth guard [{$name}] is not defined.");
    }

    if (isset($this->customCreators[$config['driver']])) {
        return $this->callCustomCreator($name, $config);
    }

    $driverMethod = 'create'.ucfirst($config['driver']).'Driver';

    if (method_exists($this, $driverMethod)) {
        return $this->{$driverMethod}($name, $config);
    }

    throw new InvalidArgumentException("Auth driver [{$config['driver']}] for guard [{$name}] is not defined.");
}



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

Is there a way to tag jobs without using Horizon?

Laravel Horizon mentions the ability to tag jobs with model IDs or any arbitrary string. I am not using Horizon but I would like to make use of this functionality, is it possible in plain Laravel? The documentation does not mention tags outside of the section on Horizon.



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

How to implement Laravel Middleware to protect task if previous is not completed

I'm building task application. It has tasks table:

tasks
--------
id
title
description

and also has user_tasks table which shows users who have completed task

user_tasks
--------
id
task_id
user_id

Task model has method which show is task completed by user

public function answered()
{
   return $this->hasOne('App\UserTask')->where('user_id', Auth::id());
}

So my goal is to make middleware which protects next task if previous isn't done for particular user. If user didn't complete task with id - 1, he can't start task with id - 2 and so one.



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

Laravel 5.5 - DB::statement error with \copy command (POSTGRES)

Im trying to use the \copy command from POSTGRES using laravel 5.5, to insert a large file at the DB, but im getting this error bellow.

I tried this way:

DB::statement( DB::raw("\\copy requisicoes FROM '".$file1."' WITH DELIMITER ','"));

Get this error:

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "\" LINE 1: \copy requisicoes FROM '/srv/www/bilhetagem_logs/bilhetagem_... ^ (SQL: \copy requisicoes FROM '/srv/www/bilhetagem_logs/bilhetagem_log1_2018-10-29' WITH DELIMITER ',')

Tried this way too:

DB::statement( DB::raw('\copy requisicoes FROM \''.$file1.'\' WITH DELIMITER \',\''));

Get this error:

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "\" LINE 1: \copy requisicoes FROM '/srv/www/bilhetagem_logs/bilhetagem_... ^ (SQL: \copy requisicoes FROM '/srv/www/bilhetagem_logs/bilhetagem_log1_2018-10-29' WITH DELIMITER ',')

If i execute the command that returns on the error above with psql line command, works fine

\copy requisicoes FROM '/srv/www/bilhetagem_logs/bilhetagem_log1_2018-10-29' WITH DELIMITER ','

Could somebody helps me? :)

I have to use \copy insted of copy becouse I dont have superuser privilege at the DB. https://www.postgresql.org/docs/9.2/static/sql-copy.html

COPY naming a file is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access.



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

Laravel Validation: Unique + RegEx

I'm trying to validate a form where a WhatsApp number should be unique regardless of spaces/hyphens/dots and whatnot so that when a record is +1 234 567 8901, entries such as +1-234-567-8901 or +1-234-567-8901 or +1.234.567.8901 should be invalid:

'custom' => [
    'attribute-name'    => [
        'rule-name' => 'custom-message',
    ],

    'whatsapp'          => [
        'unique'    =>  'WhatsApp number is already in use'
    ],
],

But what I get is Laravel's built-in validation message which is:

'regex'                => 'The :attribute format is invalid',



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

How to load new pages generated server-side into a PhoneGap or Cordova app?

I'm trying to figure out the easiest and quickest technique to adapt our company's website to an app that can be downloaded from the app stores. PhoneGap/Cordova looks the way to go. Using the InAppBrowser plugin looks like an obvious route but we're going to need access to some phone APIs via Cordova plugins and there seems no way to access data from them in the InAppBrowser (Webview?) window.

As an alternative I'm wondering why can't I simply replace the HTML content directly in my PhoneGap page (effectively a single page app) with new HTML page content loaded from our server? We're using Laravel templates server-side, so there is already a page wrapper into which Laravel injects page-specific content (on the server) before sending to the client. I could just move the page wrapper HTML to the front end (into the SPA compiled into my PhoneGap app) complete with all the JS and CSS needed across all pages, and then just live load new page content into the DOM (e.g. in the page BODY), and any JS would have access to phone APIs via Cordova plugins.

Is this feasible, or am I missing something? (any gotchas?)

Thanks.



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

Validation jQuery rules

I have a form with 2 input name and description I want to validate this two field with jquery but don't accept name how can I put this two name in rules

@foreach($languages as $language)


@endforeach

I do this in jquery but don't work any idea

@if(count($languages))
                   @foreach($languages as $language) {
                      @if($language->default)
                  form.validate({
                    /*errorElement: 'span',*/
                        errorClass: 'help-block',
                    highlight: function (element, errorClass, validClass) {
                        $(element).closest('.form-group').addClass("has-error");
                      },
                    unhighlight: function (element, errorClass, validClass) {
                        $(element).closest('.form-group').removeClass("has-error");
                    },
                        rules: {
                        "name['.$language->id.']": {
                            required: true
                        },
                        "description['.$language->id.']": {
                            required: true
                        }
                    }
                });
                    @endif
                    @endforeach
                    @endif



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

i cant install laravel-newsletter

hey guys i run the composer require spatie/laravel-newsletter in the terminal and the result is :

Using version ^4.2 for spatie/laravel-newsletter ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

Problem 1 - spatie/laravel-newsletter 4.2.0 requires drewm/mailchimp-api ^2.4 -> satisfiable by drewm/mailchimp-api[v2.4, v2.5]. - spatie/laravel-newsletter 4.2.1 requires drewm/mailchimp-api ^2.4 -> satisfiable by drewm/mailchimp-api[v2.4, v2.5]. - spatie/laravel-newsletter 4.2.2 requires drewm/mailchimp-api ^2.4 -> satisfiable by drewm/mailchimp-api[v2.4, v2.5]. - drewm/mailchimp-api v2.5 requires ext-curl * -> the requested PHP extension curl is missing from your system. - drewm/mailchimp-api v2.4 requires ext-curl * -> the requested PHP extension curl is missing from your system. - Installation request for spatie/laravel-newsletter ^4.2 -> satisfiable by spatie/laravel-newsletter[4.2.0, 4.2.1, 4.2.2].

To enable extensions, verify that they are enabled in your .ini files: - C:\php\php.ini You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.

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

i update the composer but it doesn't work for me if some one know what am i do,please help me



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

Where should i write raw-query or query using query builder instead of writing it in route file in laravel?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class testing extends Model
{

}

should i write my all queries in this model class,even if i just want to use query builder no eloquent?

what are the good practices to write raw query or using query builder?



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

How to fix error Swift_TransportException in Laravel 5.6

working with laravel 5.6 and I am going to send contact form details via the gmail. My .env file is look like this,

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myname@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=null

but when I send submit buttons following error is coming,

1/1) Swift_TransportException

Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. u21-v6sm32263983pfa.176 - gsmtp
"
in AbstractSmtpTransport.php line 383

how can fix this project?



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

Laravel: Get relationship in randomized order with condition

I have the following code where I get a random question with it's answers:

$q = Question:with(['answers' => function ($q) {
    $q->inRandomOrder();
}])->inRandomOrder()->first();

but i want like this:

$q = Question:with(['answers' => function ($q) {
    if(Question->random_answer==true){
        $q->inRandomOrder();
    }else{
        $q->orderBy('sort',' ASC');    
    }
}])->inRandomOrder()->first();

Home some one can solve this.

Thanks,

Best regard.



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

Laravel Nova: Convert Datetime to readable output

Is there an option in Laravel Nova to display an readable date-time output and/or limit the output?

For example to : 29. October 2018 / 11. November 2018, 12:10 am

Datetime



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

jquery check if 3 checboxes are checked not working on iphone

so im currently busy working on website where people can vote on 3 ideas.
I made a function that the vote submit button is disabled when someone hasnt selected 3 ideas to vote on, and when he/she does select 3 the submit becomes available.
the problem is its working perfectly fine on android phones but on iphones it stays disabled when i select 3 but becomes available when i switch from 3 to 2 or 4.
But that isnt whats supposed to happen anyone got a clue of what could be the problem.

down here is my function in JQuery

$('body').on('change','#nieuwetrofeestemmen_table',function () {
   var checked = getCheckedRows('nieuwetrofeestemmen_table');
   if(checked.length < 3 || checked.length >3){
       $('.btnStemmen').prop('disabled', true);
   }
   else {
       $('.btnStemmen').prop('disabled', false);
   }
});

thanks in advance



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

How to add row id of current user in upload

I'm working in laravel PHP in dx grid dev extreme and I'm having problem while uploading imgae. as image is saved in server but now i want to add image in db by getting users id while row is clicked... how ever I need to update the image in db and frontend as well..enter image description here

`

public function uploadImg(Request $request){

if($request['fileInput']){ 


    $fileName = time().'_'.basename($_FILES["fileInput"]["name"]);
    // dd($fileName);
   $targetDir = "storage/users/";
    $targetFilePath = $targetDir . $fileName;
      // dd($_FILES["fileInput"]["tmp_name"]);
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    $allowTypes = array('jpg','png','jpeg','gif');

    if(in_array($fileType, $allowTypes)){
       if(move_uploaded_file($_FILES["fileInput"]["tmp_name"], $targetFilePath)){
// dd($targetFilePath);
            return redirect()->back();
        }else{
            $response['status'] = 'err';
        }
    }else{
        $response['status'] = 'type_err';
    }
    echo json_encode($response);
}

}

`

dataField: "avatar",
            caption: "Add Image",
            width: 200,
            alignment: 'center',
            formItem: {
                    visible: false
                },
            width: 100,
            alignment: 'center',
            type:"button",
            cellTemplate: function (container, options) {
                $("<div />")
                    .text('Upload')
                    .on('dxclick', function () {
                        // alert('ok');

                        $('#fileInput').trigger('click',function(){
                            id: "users->id",

                           $("#imageform").onValueChanged(function(){

                       // uploadUrl: ""
                              $("#form").submit();
                            })

                        });

                    })
                    .appendTo(container);

            }
        },



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

Newly uploaded files are forriben for acccess

While my Laravel 5.7 app in PROD mode I need to upload images from my local laptop to my server, as my app has some demo data and for this I modified file /_wwwroot/lar/Votes/storage/app/public/.gitignore :

# *
# !.gitignore
tmp
.tag-details
.user-avatars
.vote-items
.votes

It means that content of tmp DIR is not uploaded to server, but new files in 4 rest folder would be uploaded to server. In PROD mode I would comment these 4 folder and new files would not be uploaded to server. Is it good decision?

But trying to open page with newly uploaded image I got 403 error(Forbidden) even after I run command

sudo chmod -R 755 /var/www/html/votes/storage/app/public/tag-details/*

and in console of my server I see :

# ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
>              *2^(8-i));if(k)printf("%0o ",k);print}'
total 68
755 drwxr-xr-x 2 root     root     4096 Oct 30 06:06 -tag-detail-1


# ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
>              *2^(8-i));if(k)printf("%0o ",k);print}'
total 28
755 -rwxr-xr-x 1 root root 26550 Oct 30 06:06 hamlet.jpg

Why error and which decision ?

Thanks!



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

Laravel Nova: Generate Model-Values without field

Is there an option to generate Model-Values by not having a form input at the nova backend?

For example after every store / update I would like to update the created_by value with the current authenticated user.

Exampl:e

$model->created_by = aut()->user()->id



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

lundi 29 octobre 2018

laravel observer cannot get data from related model

I am facing a problem while saving data through an observer. Any help from the community will be greatly appreciated. My observer is as follow.

public function created(Reservation $reservation)
{
    $from = Carbon::parse($reservation->checkin);
    $to = Carbon::parse($reservation->checkout);
    $diff_in_days = $to->diffInDays($from);

    $total_price = $reservation->rooms->sum('price') * $diff_in_days;
    dd($total_price);
}

The above code snippet perfectly works in controller, but somehow it's not working in the observer. It gets a 0 value, besides that.

$reservation->rooms;

gets an empty array, while

$reservation->rooms();

it also get belongsToMany relationship with attributes and original are empty arrays : []



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

How to send collection as an excel file in laravel

I'm using Laravel Excel 3.1 from https://laravel-excel.maatwebsite.nl/ and I am trying to figure out if there is a simple way to simply render a collection as an excel file.

In my controller, I have code that generates a db query and puts it into a view. I'd like to give the user the ability to download the data in that view as an excel document. The code used to create the view is not simple, and it is based on many query inputs.

In my controller, I have

public function excelExport(Request $request)
{
    $params = $this->getQueryParams($request);
    $pts = $this->createIndexCollection($request, $params);

    return Excel::download(new PatientsExport, 'patients.xlsx');
}

I'd like to pass the already-computed collection $pts to the download command. Is this possible?



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

Using Phpredis in Laravel 5.7

I have read the docs.

I have changed the database.php file, once this is done I have deleted the predis package from my vendor.

composer remove predis/predis

But when I do a composer update or any artisan command I get this error:

In PredisConnector.php line 25:

  Class 'Predis\Client' not found

enter image description here

Why do I need predis if I am already using phpredis?



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

Laravel Nova: Select-Field with other models

Is there a way to create a Select-Field with other models? For example User::all()?

Workaround: Select Field

In the app I would like to select from available Users:

Laravel Nova: Select Users



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

how to make custom login in laravel 5.6?

I have used my own custom login without using auth. Here is my code

 public function userLogin(Request $request){

  if($request->isMethod('post')){
    $data = $request->input();

    $this->validate($request, [
        'uemail'=> 'required|email',
        'user_type'=> 'required',
        'user_id' => 'required',
        'upassword' => 'required|min:6',
      ],
      [
        'uemail.email' => 'Email must be valid',
        'uemail.required' => 'Email is required',
        'user_type.required' => 'Type is required',
        'user_id.required' => 'Name is required',
        'upassword.required' => 'Password is required',
        'upassword.min' => 'Password must be at least 6 characters',
      ]);

      $user_type = $data['user_type'];
      $user_id = $data['user_id'];
      $uemail = $data['uemail'];
      $upassword = $data['upassword'];
      $hashPass = bcrypt($upassword);

      DB::enableQueryLog();

      $user1 =  User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
      ->where('status',1)->where('deleted_at',null)->firstOrFail();

      $user =  DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
      ->where('status',1)->where('deleted_at',null);

    //  $query = DB::getQueryLog();
     // $query = end($query);

      $isPasswordCorrect = Hash::check($upassword, $user1->password);

      if($user == null){
        echo "Failed"; die;
      }

       if($user->exists() && $isPasswordCorrect){
          echo "Success"; die;
          Session::put('userSession',$user1->email);
          Session::put('loginSession',$user_type);
          Session::put('idSession',$user1->user_id);

         return redirect('/user/dashboard');
    } else {
       return redirect('/user')->>with('flash_message_error','Invalid Login Credentials..');
    }

  }

    return view('death_notice.user_login');
}

This is my login function. But its not working. When the credentials is right it redirects to dashboard i.e that's correct, but when the credentials is wrong it is not showing error message and says 404 page not found.

I want to have the solution of this problem.



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

Why update picture doesn't detect file uploaded?

I am using laravel 5 to create an edit form for a profile and can update picture in the form.

I want to store a new image in edit form. I use this code in edit.blade to get the image by user.

  {!! Form::model($dataItemregistration,['method' => 'PATCH', 'action' => ['Modul\ProfilController@update', $dataItemregistration->ItemRegistrationID, 'files' => true] ]) !!}

  <div class="form-group">
            <div class="row">
                <div class="col-lg-3"> 
                  
                </div>
                <div class="col-lg-7">
                  {!! Form::file('gambar', array('class' => 'form-control')) !!}
                </div>
            </div>
        </div>
          <br>
      <div class="col-lg-10 text-center">
        {!! link_to(URL::previous(),'Back', ['class' => 'btn btn-warning btn-md']) !!}

        

        {!! Form::close() !!}

in controller update:

  public function update(Request $request, $id)
{
    $valueitemregistrations = Itemregistration::find($id);

     $this->validate($request,['gambar' => 'max:100000',
     ]);
     if ($request->hasFile('gambar')) {
    // Get the file from the request
    $file = $request->file('gambar');
    // Get the contents of the file
    $content = $file->openFile()->fread($file->getSize());

    $valueitemregistrations->Picture = $content;
    $valueitemregistrations->update();


        if($valueitemregistrations)
            return redirect('profil');
        else
            return redirect()->back()->withInput();
      } else { 
       echo "testing";
      }
     }

When I try to upload and update, it goes to echo "testing". It doesn't detected any files uploaded..

I had been using the same code for add.blade and it works.

Is it related to route path or else?



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

How to reduce loading time required to display the output?

I use this query to get a list of data from database and then display it using datatable. However, the query take longer time to load the data before converted to datatable. This application is built in laravel 5.

 $itemregistrations = DB::table('itemregistrations')
                     ->join('sections', 'itemregistrations.sectionid', '=', 'sections.sectionid')
                     ->join('categories', 'itemregistrations.categoryid', '=', 'categories.categoryid')
                     ->join('operasi', 'itemregistrations.operasiid', '=', 'operasi.operasiid')
                     ->select('itemregistrations.*', 'sections.sectionname', 'categories.categoryname', 'operasi.operasiname')
                     ->get();

How to reduce loading time to display the output? Before this I use pagination and it works..However i cannot using paginate when using datatable as it doesn't search through all the queries when using paginate. It will only search on the first page of pagination.



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

After updating Laravel composer blank page coming

I added in google mapper require in composer.json and updated it seccesfully. But when try to connect my page. Just seeing blank page. No error or something. just blank page.

this is the log.

Package operations: 1 install, 2 updates, 0 removals - Updating laravel/framework (v5.7.10 => v5.7.11): Downloading (100%)
- Updating spatie/laravel-backup (5.11.1 => 5.11.2): Downloading (100%)
- Installing cornford/googlmapper (v2.33.0): Downloading (100%) Writing lock file Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump @php artisan package:discover Discovered Package: beyondcode/laravel-dump-server Discovered Package: cornford/googlmapper Discovered Package: fideloper/proxy Discovered Package: kyslik/column-sortable Discovered Package: laravel/tinker Discovered Package: nesbot/carbon Discovered Package: nunomaduro/collision Discovered Package: spatie/laravel-backup Package manifest generated successfully.

Any idea why is this happining?



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

API Routing Laravel 5.5

I have basic controller, where I want it to receive any json request. Am new to api routing. I get Sorry No Page Found When I use POST MAN. First I tested it on GET and made it call a simple return but throws the error."Sorry, the page you are looking for could not be found." I removed the api prefix in the RouteServiceProvider.php and to no success.I put my demo controller

Routing api.php

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/


Route::get('/test_api/v1', 'TestController@formCheck');

TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
  public function formCheck(){
    return "YES !!!";
  }

  public function formPost(Request $request)
  {
    $formData = $request->all();
    return response()->json($formData, 201);

  }
}



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

laravel 5- get related products by search in Many To Many

Table 1: products: id,title
Table 2: features: id,name,values
Table 3:feature_product:id,product_id,values

I want get all related products when I search in values in feature_product table.

I do these:

in product model:

public function features()
{
    return $this->belongsToMany(Feature::class)->withPivot('values');
}

public function feature()
{
    // ???
}

and query for search:

 $q = 'yellow';
 $query->where(function($query) use ($q)
 {
    $query->WhereHas('feature' , function ($query) use 
    ($q){$query->where('values' , 'LIKE' , '%' . $q . '%' );});
 }

how can I search in related features of products? (and get those products)

I think I must do something in this function in product model:

public function feature()
{
        // ???
}



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

Set class active on click navigation link

I need help setting a link as active upon clicking on my html top nav bar.

The nav bar looks like this

   <div class="collapse navbar-collapse pull-left" id="navbar-collapse">
    <ul class="nav navbar-nav">
      <li>
          <a href="">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Clients <span class="caret"></span></a>
          <ul class="dropdown-menu" role="menu">
            <li><a href="">Add New Client</a></li></i></a></li>
          </ul>
      </li>
    </ul>
   </div>

So when i click Home it must highlight Home when i click on Clients it must highlight Clients. I really don't know how to achieve this so any help will be very much appreciated.



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

Query Builder Eloquent Where clause for TimeStamp - Laravel 5.1

I have a table and search bar.

enter image description here

When user input in the search that when I grab that and query my database.

This is what I got

public function getLogsFromDb($q = null) {

    if (Input::get('q') != '') {
        $q = Input::get('q');
    }
    $perPage = 25;

    if ($q != '') {

        $logs = DB::table('fortinet_logs')
            ->orWhere('account_id', 'like', '%'.$q.'%')
            ->orWhere('cpe_mac', 'like', '%'.$q.'%')
            ->orWhere('p_hns_id', 'like', '%'.$q.'%')
            ->orWhere('g_hns_id', 'like', '%'.$q.'%')
            ->orWhere('data', 'like', '%'.$q.'%')
            ->orWhere('created_at', 'like', '%'.$q.'%')
            ->orderBy('updated_at', 'desc')->paginate($perPage) <----🐞
            ->setPath('');


            //dd($logs);

        $logs->appends(['q' => $q]);

    } else {

        $logs = DB::table('fortinet_logs')
            ->orderBy('created_at', 'desc')->paginate($perPage)
            ->setPath('');
    }

    return view('telenet.views.wizard.logTable', get_defined_vars());

}


Result

In the network tab, I kept getting

Undefined function: 7 ERROR: operator does not exist: timestamp without time zone ~~ unknown

enter image description here


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



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

How to fix **Swift_TransportException** in Laravel 5.6

I am going to send contact form details via the gmail. My .env file is look like this,

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myname@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=null

but when I send submit buttons following error is coming,

 (1/1) Swift_TransportException

Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. u5-v6sm3569015pgk.46 - gsmtp
"

then How Can I fix this problem?



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

Does hasManyThrough ignore global scopes on the intermediate table?

I have 3 tables: companies, games and tests.

  • Companies have many games
  • Games have many tests

The Game model has a global scope, which I can confirm is working:

public function apply(Builder $builder, Model $model)
{
    $builder->where('type', 'live');
}

Any direct queries I do using the Game model will only return results where the game type is set to "live".

I am using return $this->hasManyThrough('App\Test', 'App\Games') in my Company model to get all tests for a particular company.

However, this is returning results for all games, regardless of their type.

So I am wondering if using hasManyThrough bypasses the global scope that I've set in the Game model?

If so, is there any way around this? I want to make sure that all queries I'm doing are filtering out any games that aren't set to "live".

Cheers



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

Eloquent manytomany polymorphic nested query withCount

I have the following manytomany polymorphic relationship

Asset

public function countries()
{
    return $this->morphToMany('App\Country', 'locationable');
}

Country

public function assets()
{
    return $this->morphedByMany('App\Asset', 'locationable');
}

Also Category has manytomany with Assets

public function assets()
    {
        return $this->belongsToMany('App\Asset', 'category_asset');
    }

I need to query a category and eager load assets that have country assigned.

Here is my eloquent query

$category = Category::with(['children.assets' => function ($query) {
            $query->whereHas('countries', function($q) {
                $q->where('code', '=', 'FR');
            });
        }])
            ->where('id', 1)
            ->first();

This seems to work, but then when I use the Category model with $this->assets It loads all of them, even if only one is returned in the query.

I am using API resources like so

AssetResource::collection($this->whenLoaded('assets'))

Where can I put a condition to only use assets that passed the condition where('code', '=', 'FR')



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

Duplicate Queries in Laravel- Debugger

I am trying to update the columns of the records based on the other column records but it results in the duplicate queries since its being executed for each record in the table.I s there a way to avoid it and improve this code.

 public function updateReviewColumn(){
        $reviewData = $this->pluck('indicator')->toArray();
        foreach ($reviewData as $datum) {
            if ($datum == 'Y')
                $this->where('indicator', $datum)
                    ->update(['reviewindicator' => 'Yes']);
            else
                $this->where('indicator', $datum)
                    ->update(['reviewindicator' => 'No']);
        }
    }



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