vendredi 30 avril 2021

How to return values in array of json using laravel query?

$search='m';
$data = Product::select("product_name")
        ->where('product_name','LIKE', '%' . $search . '%')
        ->get();
    
 return response()->json($data);

It returns

[{"product_name":"MyProduct"},{"product_name":"MAC"}] .....

But I want [{"MyProduct"},{"MAC"}]



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

Laravel Broadcast on demand

on documentation laravel about notification on demand it's only have example for mail,slack and nexmo so how to send notification via broadcast use on demand. https://laravel.com/docs/5.8/notifications

that example for mail

Notification::route('mail', 'taylor@example.com')
        ->route('nexmo', '5555555555')
        ->route('slack', 'https://hooks.slack.com/services/...')
        ->notify(new InvoicePaid($invoice));

or how to send notification broadcast without Elequent.



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

Get Departmenr name from department id using eloquent laravel

I have this user table

id | name |      email     | department_id

1    user 1  xyz@gmail.com        2

and this is department table

id |  department_name 

1      Admin 
2      Account

there is salary table :

id |  user_id |  basic_pay

1        1          5000

I have this employee relation in salary model

class Salary extends Model
{
   public function employee(){
      return $this->belongsTo('App\User','user_id','id');
   }
}

I want to get department name also to which user is associated

  $Data =  Salary::where('id',$id)->with('employee')->first();

but presently i can only get department_id with the help of employee relation.

Any help is highly appreciated.



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

Laravel Coinpayment Issue "HMAC signature does not match"

Hello guys please i need help with this issue,i used coinpaymentHosted Lib ,i have set the creditiate correct but i am having this error message when i try to proccess transaction here is my code,

    $cps = new CoinPaymentHosted();
    $cps->Setup($gate->val2,$gate->val1);
    $callbackUrl = route('user.callback.coinpayment');

    $req = array(
        'amount' => (FLOAT) $Amountcharge,
        'currency1' => 'USD',
        'currency2' => $request->selectcrypto,
        'custom' => $transactionRecord->uuid,
        'ipn_url' => $callbackUrl,
        'cancel_url' => route('home'),
        );
    $result = $cps->CreateTransaction($req);
     dd($result);

i dont know if i am getting anything wrong or it coming from coinpayment, i have also install this package https://github.com/hexters/CoinPayment and set it according to usage but i still get the same error "HMAC signature does not match"



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

jeudi 29 avril 2021

how to loop through data from many to many relationship laravel?

i am trying to get the name of the supplier of each product but when i do this

 @foreach ($products as $product )
    <tr>
      <th scope="row"></th>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
@endforeach

it says Property [name] does not exist on this collection instance however when i do this

<td></td>

this is what is what it shows me [{"id":1,"name":"test","address":"test","created_at":null,"updated_at":null,"pivot":{"product_id":1,"supplier_id":1}}]

so i think the relationship exists i just cant figure out how to loop through it

side note : i did indeed insert data through phpmyadmin and not seed ,



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

Facing issue while implementing JWT Auth Laravel

Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.Apache Server at xphenoconnect.com Port 80



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

Node js socket.io broadcast only for particular events subscription

Now I have a small program in Laravel to serve the stock market rates via events. When ever the rates gets update it will update the rates to redis and broadcast from node js application to clients.

Here I have created 3 events like ounce rate, MCX rates and comex rates. My socket.io program as like,

redis.subscribe('mcxratesupdate', function(err, count) {
    
});

redis.subscribe('ounceratesupdate', function(err, count) {
    
});

redis.subscribe('comexratesupdate', function(err, count) {
    
});

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

server.listen(3002, function(){
    console.log('Listening on Port 3002');
});

In my client having the code like,

$(function () {
    var socket = io.connect('http://myhost:3002/', { secure: true, transports: ['websocket'], rejectUnauthorized: false, reconnect: true });
    socket.on("mcxratesupdate:App\\Events\\MCXRateUpdates", function(data){
        console.log(data);
    });
});

This is working fine, But if the event ounceratesupdate get fires that response also broadcast to this client. So all the events in this single server data getting broadcast to client. How to avoid all the events data sharing and only share particular event data.



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

mercredi 28 avril 2021

LdapRecord Laravel - Active Directory - does not see any users

I am using the ready package as a base, I have done all steps in the readme.md file and was able to login as "einstein" user. So all seems to be configured correctly.

Later I have changed the credentials for the ldap server, which is using Active Directory.

While runing command php artisan ldap:test i receive message that i was able to connect correctly. Laravel logs says the same, but I cannot log in to laravel app. While running the command php artisan ldap:import ldap get message that no users where find

In the log file i see something like this:

[2021-04-28 23:04:08] local.INFO: LDAP (ldap://domain.pl:389) - Operation: Search - Base DN: cn=username@domain.pl,ou=Users,dc=domain,dc=pl - Filter: (&(objectclass=top)(objectclass=person)(objectclass=organizationalperson)(objectclass=inetorgperson)(uid=username)) - Selected: (entryuuid,*) - Time Elapsed: 737.37  

Have anyone had the same issue with the ldaprecord that he was able to connect to domain but wasn't able to authenticate to an app ? And was able to solve that ?

UPDATE: i've found that auth.php is using wrong User model, it was using OpenLdap not Active directory, changed that but result is still the same



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

Obtain customer collection with filtered addresses in Eloquent

I have this two models:

   customers(id,firstname,lastname,phone)
   addresses(id,city,address,customer_id)

With relation:

 class Customer extends Model
 {

     public function addresses()
     {
         return $this->hasMany(Address::class);
     }
 }


 public function customer()
     {
         return $this->belongsTo(Customer::class,'customer_id');
     }

And I'm trying to obtain customers with address in certain city

  return new CustomerCollection(Customer::has('addresses')
                       ->with(array('addresses' => function($q) use ($field)
                        {
                          $q->where('province_id','like',$field)->get();

                        }))->orderBy('id','DESC')->paginate(100));

Result is fine, I obtain correct customers collection, but addresses array is empty. What's wrong?



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

Laravel Run on virtual host domain then validation not working

Hello i have run laravel created virtual host abc.dev and post form then validation not working

After i have run using ip address 127.0.0.1 then validation working

Any body face this issue?



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

Show Specific Array Images in Modal Using Laravel & jQuery AJAX

I need to show specific image from array images, but I can't do it. Below what I've tried!

Array Images

Controller

public function edit($id)
{
    $product = \App\Product::find($id);

    $picts = [];
    foreach (json_decode($product->product_photo) as $picture) {
        $picts[] = $picture->path;
    }

    $pix = [];
    for ($i = 0; $i < count($picts); $i++) {
        $pix[$i] =
            '<input type="hidden" name="photo_id" id="photo_id' . $i . '">
            <div class="array-images-forEdit" style="position:relative;float:left;margin-right:5px;"><button type="submit" style="position:absolute;top:0;left:0;top:2px;left:5px;margin-left:80px;" class="close-forEdit" aria-label="Close"><span>&times;</span></button><a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $product->id . '"  data-filter="/reference/eureka/storage/app/' . $picts[$i] . '" data-original-title="Edit" class="showModalPhoto" id="showModalPhoto"><img id="myImage" src="/reference/eureka/storage/app/' . $picts[$i] . '" style="height:120px;width:105px;margin-bottom:10px;top:0;right:0;"/></a></div>
            ';
    }
    $pix = implode(' ', $pix);

    $html =
        '
    <div class="row">
    <div class="col-md-12">
    ' . $pix . '
    </div>
    </div> <!-- row-->';

    return response()->json(['html' => $html, 'product' => $product->category]);
}

Array Images Preview enter image description here

Now, when I click one of image above, it should display specific image in modal. But I can't do it. It show all images. Below the result!

Controller

 public function showPhoto($id)
    {
    $product = \App\Product::find($id);
    $picts = [];
    foreach (json_decode($product->product_photo) as $picture) {
        $picts[] = $picture->path;
    }

    $html = [];
    for ($i = 0; $i < count($picts); $i++) {
        $html[$i] =
            '<div class="row">
        <div class="col-md-4">
        <img src="/reference/eureka/storage/app/' . $picts[$i] . '" style="height:500px;width:465px;margin-bottom:10px;top:0;right:0;"/>
        </div>
     </div>';
    }

    return response()->json(['html' => $html]);
} 

View

$('body').on('click', '#showModalPhoto', function(e) { // .editUser exist in usercontroller.php

        e.preventDefault();
        $('.alert-danger').html('');
        $('.alert-danger').hide();

        id = $(this).data('id');

        $.ajax({
            url: "product/" + id + "/show-photo",
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                $('#dataPhotoElement').html(data.html);

                $('#photo_id').val('');
                $('#productForm').trigger("reset");
                $('#modelHeading').html("Show Photo");
                $('#ajaxModelForPhoto').modal('show');
            }
        });
    });

Modal View enter image description here



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

Laravel Eloquent Model can't sync with pivot data in Many-to-Many relationship

I would like to sync the data instead of attach the data to the particular relationship.

Pivot relation UserModel code

public function carts(){
        return $this->belongsToMany(Product::class,'user_carts')->withPivot('quantity');
    }

The attach code is

User::find(1)->carts()->attach($s,["quantity"=>1]);

The sync code is

User::find(1)->carts()->sync($s,["quantity"=>1]);

When I try to compile the sync, those pivot relation that matched user_id = 1 does not have the "1" in its respective quantity column.

If I would like to achieve the sync function without using attach, how can I do it because the attach() will create multiple redundant data in my database.



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

mardi 27 avril 2021

Return 404 in Laravel RouteServiceProvider

I want to give a 404 response if index.php is found in the url. example url is domain.com/index.php/about

expected : return blade 404

I've tried this code but can't get the 404 display

class RouteServiceProvider extends ServiceProvider
{
    protected $namespace = 'App\Http\Controllers';

    public function boot()
    {
        parent::boot();
    }

    public function map()
    {
        $this->removeIndexPhpFromUrl();
    }

    protected function removeIndexPhpFromUrl()
    {
        $currentUrl = url()->current();
        if(strpos($currentUrl, 'index.php') !== false){
            return view('errors.404');
        }
    }
}



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

method injection in laravel

hi guys i am new in laravel i have been reading about service container but i have one question about method injection laravel has its limits regarding method injection as far as i know we can only use method injection inside 3 methods (places) first , all public methods inside constructor second , boot method inside any service provide , third , handle method inside queue jobs is there any other methods we can use method injection inside ?

namespace App\Http\Controllers ;

public function store(request $request,User $user) {

   dd($user) //it works 
}

and also works inside boot method inside service provider and inside laravel queue jobs is there any methods?



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

How to fetch the data from the server in jquery? [closed]

I use laravel and jquery.

I have 4 divs in my view. I need to fetch the time() from the server and to display it in each div's.

View:

<div id="div1"> </div>
<div id="div2"> </div>
<div id="div3"> </div>
<div id="div4"> </div>

Controller:

class SampleController extends Controller
{
    public function getcurrentTime($divId = null)
    {
     $result = time();
     return view('welcome');
    }
}

In Sample.js:

$(document).ready(function(){
  function myFunction() {
  document.querySelectorAll('*').forEach(function(node) {
    ajax = $.ajax({
      url: '/SampleController/getCurrentTime/' . node,
      method: 'post',
      dataType: 'json',
      success: function(data) {
         if (data === true) {
            trueFunction(data);
         } else {
            falseFunction(data);
         }
         ajax = null;
      }
    });

    node.innerHTML = ajax.data;

  });
}
  function trueFunction(data) {
      element.html('Success: ' + data);
   }

   function falseFunction(data) {
      element.html('Failed: ' + data);
   }

    });

In web.php

Route::post('SampleController/getcurrentTime', 'SampleController@getcurrentTime');

Getting an error

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.

Could someone please help.

Thanks



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

Laravel 8 return blank page

In controller;

 public function list_of_approved_policies(){
    
      dd("I am here");
      die(); 
    } 

In route

Route::get('/listofapprovedpolicies','MerchantDashboardController@list_of_approved_policies');

When I calling /listofapprovepolicies Laravel return just white blank page. How can i solve this problem ?



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

500 Whoops, something went wrong on our servers [closed]

PLEASE HELP ME HOW TO SOLVE THIS ERROR



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

Need to get data with laravel when query

I am trying to filter data using when query in Laravel, where it should filter data using the filter $sortBy or $categoryId. Please note the all 3 fields like $id $sortBy $categoryId are optional and will not be presented in all queries

public function Products(Request $request)
{
    $page     = $request->has('page') ? $request->get('page') : 1;
    $limit    = $request->has('itemsPerPage') ? $request->get('itemsPerPage') : 10;
    $sortBy = (($request->sortBy == "popularity")  ? "viewCount" : "created_at");
    $categoryId=  $request->get('categoryId');

    $sellerId = $request->header('id')?SellersBranding::findOrFail($request->header('id')):"Null";
    
    $productLive = ProductsLive::select('productTitle', 'product_id', 'brand_id', 'category_id')
        ->when($sellerId=="Null", function($query)  use ($page, $limit){
            return $query->where('status', 'active')
            ->limit($limit)->offset(($page - 1) * $limit);
        })
        ->when($sortBy, function ($query) use ($sortBy, $sellerId, $page, $limit){
            return $query->orderBy($sortBy, 'DESC')
                ->where('Sid', $sellerId->id)
                ->where('status','active')
                ->limit($limit)->offset(($page - 1) * $limit);
        })
        ->when($categoryId, function ($query) use ($categoryId, $sellerId, $page, $limit) {
            ->where('Sid', $sellerId->id)
                ->where(['category_id' => $categoryId, 'status' => 'active'])
                ->limit($limit)->offset(($page - 1) * $limit)
                ->inRandomOrder();
        })->get();
}

i am new in php and also in laravel please help how to get filtered data



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

lundi 26 avril 2021

How to create a test for a pivot table?

I want to create a test for the controller. There are three tables, Roles, Categories and Categories_roles, the connection is many to many.

Controller:

/**
 * Update connections.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function update(Request $request) {

    $input = $request->get('category', []);
    foreach (Category::all() as $category) {
        $category->roles()->sync(Arr::get($input, $category->id, []));
    }
    return view('home');
}

I can not figure out how to write a test, there is a view in my head but I don't know how to implement. How I started to do.

Test:

/** @test */
public function test_admin_user_can_edit_categories_roles()
{
    $this->actingAs(\App\Models\User::factory()->create(['role_id' => 1]));
    $input = [
        "1" => [
            "1" => "1"
        ],
        "2" => [
            "1" => "1"
       ],
    ];
    $this->post('/admin/connections', $input);
}


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

Larave BelongsTo relationship returns null

I have two Eloquent models:

1) Project :

class Project extends Model
{
    protected $table = 'projects';
    protected $fillable = ['id', 'user_id', 'account_id'];

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

    public function account()
    {
        return $this->belongsTo(Account::class, "account_id");
    }

2) Account :

class Account extends Model
{
    // ...

    public function projects(){
        return $this->hasMany(Project::class);
    }

The goal is to have returned the account of the project :

Project::with("account")->get()->pluck("account");

Result :

null


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

Issue with Laravel casting Int to string when fetching from server?

I have my web application running on server. I tested the code in local and it works fine. I'm getting id as int from local server but string in hosted server.

Using PHP 7.3

$data = DB::table('users')
->select('id')
->get();

$data = $data->pluck(id);

(Local) output => [1,2,3]

(Hosted) output => ["1","2","3"]

Can any one help to resolve this issue? I can do loop to type cast but there are 100's for function in my controller. It is not possible to type cast each query.



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

How to use bunnycdn laravel module?

I found BunnyCDN Module on GitHub, I want to use the module for my laravel application. Anyone, please tell me how can I do that?

Github Link: https://github.com/PlatformCommunity/flysystem-bunnycdn

Thank you.



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

dimanche 25 avril 2021

Laravel DB facade nested array for relatioships

I work with huge database, with many tables, so I prefered working with DB facade instead of Eloquent models.

I have two tables with one-to-many relationship (although foreign key is not declared):

                     +-------------+
+-----------+        | orders      |
| clients   |        +-------------+
+-----------+        | order_id    |
| client_id |<-------| client_id   |
| name      |        | details     | 
+-----------+        +-------------+

I would like to achieve the same result as I would do using with() function:

[
   [
      'client_id' => 1,
      'name' => 'Alfonso',
      'orders' => [
         [
            'order_id' => 32,
            'details' => 'Loren Ipsum'
         ],
         [
            'order_id' => 34,
            'details' => 'Loren Ipsum'
         ]
      ]
   ],
   [
      'client_id' => 2,
      'name' => 'Beatriz',
      'orders' => [
         [
            'order_id' => 15,
            'details' => 'Loren Ipsum',
         ],
         [
            'order_id' => 19,
            'details' => 'Loren Ipsum',
         ],
      ]
   ]
];

I can do it with simple foreach function, I wonder whether there is some way to use something similar to with() function although I don't use models.

The basic query looks like this:

$res = DB::table('clientes')
    ->leftJoin('orders', 'orders.client_id', '=', 'cliends.client_id')
    ->get()->toArray();


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

Display Multiple Images in Laravel Datatables

I am trying many times to show multiple images in datatables, but it always failed. It's only display single image.

Images in database

[{"name":"_MG_2288 (1).jpg","path":"public\/product_images\/\/mKBWAFw7ZYgVqvz1lrxrEA5PYbal1EqqKm9jEx0F.jpg"},{"name":"555dca050423bda8418b4567.jpeg","path":"public\/product_images\/\/QnYnO9SfA9JJIu7wm0rxJOIJog6txmED8pdiZ4nM.jpg"}]

Controller

$data = \App\Product::latest()->get();

        return Datatables::of($data)
            ->addIndexColumn()
            ->addColumn('photo', function ($product) {
                foreach (json_decode($product->product_photo) as $picture) {
                    $pict = '<img src="/reference/eureka/storage/app/' . $picture->path . '" style="height:120px; width:200px"/>';
                    return $pict;
                }
            })
            ->rawColumns(['photo'])
            ->make(true);


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

Controller returning null on eloquent query in laravel 5.8 phpunit test

I am trying to create a mock for model ProjectRating where I want to return a specific value based on whatever the query for the model is. With select and first I am receiving the set result value but I am getting null when I have a where in the query.

My Query in the controller looks like this

$projectRating = ProjectRating::select('rating')
                ->where('project_id', $projectId)
                ->where('country_id', $countryId)
                ->where('language_id', $languageId)
                ->first() ;

and my test code looks like this

$fakeProjectRating = \Mockery::mock(ProjectRating::class);

$fakeProjectRating->shouldReceive('select->where->where->where->first')->andReturn(['rating'=>'c']);

app()->instance(ProjectRating::class, $fakeProjectRating);

Thanks in advance



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

Cant Upload Multiple Images In Laravel jQuery AJAX

I've stuck many days when I am trying to upload image files. I can't upload multiple images files with code below:

Controller

if ($request->TotalImages > 0) {

            for ($x = 0; $x < $request->TotalImages; $x++) {

                if ($request->hasFile('images' . $x)) {
                    $file      = $request->file('images' . $x);

                    $path = $file->store('public/product_images/');
                    $name = $file->getClientOriginalName();

                    $insert[$x]['name'] = $name;
                    $insert[$x]['path'] = $path;
                }
            }
        }

        $productId = DB::table('products')->insertGetId(
            [
                'product_photo' => $insert
            ]
        );

View

<input id="images" name="images[]" type="file" multiple
                            class="form-control "
                            data-iconName="fa fa-upload" data-overwrite-initial="false">
                        <br>
var formData = new FormData();
let TotalImages = $('#images')[0].files.length; //Total Images
        let images = $('#images')[0];
        for (let i = 0; i < TotalImages; i++) {
            formData.append('images' + i, images.files[i]);
        }
        formData.append('TotalImages', TotalImages);

        $.ajax({
            url: "",
            method: 'post',
            enctype: 'multipart/form-data',
            cache: false,
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            async: true,
            headers: {
                'Content-Type': undefined,
            },
            xhr: function() {
                myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            
        }); //ajax

It always show me an error:

The images field is required.

But with single upload it works!



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

samedi 24 avril 2021

Laravel 5.6 - add extra input to login

In my users table I have a memorable_info column that contains a bcrypt value. I also have this as a field on my login form. So my login form fields in total are...

  • email
  • password
  • memorable_info

Obviously, I only want users to be logged in if they enter all 3 fields successfully. However, I cannot get it to check the memorable_info field. In my LoginController.php file, I have included the Auth facade and added the following functions...

protected function credentials(Request $request)
{
    return $request->only('email', 'password', 'memorable_info');
}

public function authenticate(Request $request)
{
    if (Auth::attempt(['email' => $request->email, 'password' => bcrypt($request->password), 'memorable_info' => bcrypt($request->memorable_info)])) {
        return redirect()->intended('dashboard');
    }
}

...however, this does not work and I constantly get the "These credentials do match our records." error.

Hoping someone has the answer on this please?



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

How to pass the date within an array to the database in laravel

I have made the following migration in Laravel:

public function up()
{
    Schema::create('attendances', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('student_id');
        $table->date('att_date')();
        $table->string('status');
        $table->timestamps();
    });
}

My Form in Blade look like this

<form method="post" action="" enctype="multipart/form-data">
  @csrf 
  <div class="row">
    <div class="col-md-4"></div>
    <div class="form-group col-md-4">
      <strong>Date : </strong>
      <input class="date form-control"  type="text" id="datepicker" name="att_date[]">
    </div>
  </div>
  <div class="mb-3">
    <table>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Level</th>
        <th>Status</th>
      </tr>
      @foreach($students_att as $student)
        <tr>
          <td></td>
          <td></td>
          <td></td>
          <td>
            <input type="hidden" id="custId" name="student_id[]" value="">
          </td>
          <td>
            <select name="status[]">
              <option value="0">No</option>
              <option value="1">Yes</option>
            </select>
          </td>
        </tr>
      @endforeach
    </table>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>

<script type="text/javascript">
  $('#datepicker').datepicker({
    autoclose: true,
    format: 'yyyy-mm-dd'
  });
</script>

and I have made my Controller like this:

public function sumbit(Request $request)
{
    /* $submit = new Attendance;
    $submit->student_id = $request->get('student_id');
    // $submit->att_date = $request->get('att_date');
    // $submit->status = $request->get('status');
    $submit->save();
    return redirect('att'); */

    $studentID = $request->input('student_id', []);
    $studentDate = $request->input('att_date', []);
    $studentStatus = $request->input('status', []);
    
    $students = [];
    
    foreach ($studentID as $index => $student) {
        $students[] = [
            "student_id" => $studentID[$index],
            "att_date" => $studentDate[$index],
            "status" => $studentStatus[$index],
        ];
    }
    
    $create = Attendance::insert($students);
}

so I want when i submit my form, it must be record the same date that i used by date picker to every input that show in the following image to my database image

but when i did this procedure, i got this error (ErrorException Undefined offset: 1) the error in this line in my controller line

"att_date" => $studentDate[$index],

How can Ii fix this error please help



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

laravel orm : sort by id but put 0 values of another column at the end

I have a Products table

products: id, title, stock, price

I want new products to be at top of the list (first page), but I also want products with 0 stock to be at the end of the list (last page)

obviously, this doesn't work the way I want it, a new product with 0 stock still will show up first

Product::orderBy('id' , 'desc')->orderBy('stock' , 'desc')->paginate(20)

there are lots of similar questions but all seem to be about null values which don't work for me .. also I tried

->orderByRaw('stock = 0', 'ASC', 'id' , 'desc' )->paginate(20)

as was suggested but I get an empty collection

it's a pagination query, sort has to happen in the database, and sorting the collection after reading them from DB won't work

------------------------------------ EDIT ------------------------------------

i tried this code

Product::orderByRaw('stock = 0', 'ASC')
            ->orderBy('id' , 'desc')
            ->get()

which will generate this query in debugger

select * from `products` order by stat_view = 0, `id` desc

this code will work when i try it directly in database , but for some reason in laravel i get an empty collection .... this is an old website which is using laravel 5.2 not sure if that has anything to do with the problem

enter image description here



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

Call to a member function subjects() on null

i'm facing an error Call to a member function subjects() on null . My project is by php and laravel. My project is on live server. Its works fine normally but when i click to edit something or click update button then it shows Call to a member function subjects() on null . Only my current browser facing this error but if i hit from another browser to my server its seems ok.

public function index()

{

    $featured_packages = Package::where('featured_package', 1)

        ->with('reviews', 'user')

        ->get();

    $popular_packages = Package::where('popular_package', 1)

        ->with(['class' => function ($query) {

            $query->pluck('name');

        }, 'reviews', 'user'])

        ->withCount('mcqs')->get();

    $class_id  = StudentClass::all()->random()->id;

    if (Auth::check()) {

        $class_id = auth()->user()->grad != '' ? auth()->user()->grad : $class_id;

    }

    $subjects = StudentClass::find($class_id)->subjects()->withCount('packages')->get();

    return view('frontend.index', compact('featured_packages', 'popular_packages', 'subjects', 'class_id'));

}

public function about()

{

    $about = About::orderBy('id', 'desc')->first();

    return view('frontend.about', compact('about'));

}

public function contact()

{

    return view('frontend.contact');

}

public function faqs()

{

    $faqs = Faq::orderBy('id', 'asc')->where('status', 1)->get()->groupBy('tab');

    return view('frontend.faqs', compact('faqs'));


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

vendredi 23 avril 2021

Get Start and end date of Week according to string

I want to display the start date and end date of the week. I have One date and a string like 1W4 and,in 1W4 consider 4 weeks and 1 visit so, my string like this 2W4,1W2,3W3,1W1,2W4.

I want to make start date and end date of week array according to string and week start from Sunday to Saturday.

Please post me if anyone has solution.Please ignoring if mistake in asking Question.

Thank you.



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

how can some one hack into deployed public_html directory with laravel 5.4 deployed project

i've server ubuntu with laravel 5.4 and it works fine for some time, it has cpanel and deployed on siteground, after few days, i find weird files been uploaded to the public_html directory and server stop handling requests? here's a screenshot with files been uploaded, how can i identify the problem? that can't be a code problem right? i've no idea where to look? shall i change the host? i changed the password and everything i could.

enter image description here



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

i have problem to run laravel 5 project on local

i cloned a Laravel 5 project and try to run it . i got some errors in composer install composer update php artisan migrate

(actually all of "php aritsan" commands)

i got this error :

In Connector.php line 70:

  SQLSTATE[HY000] [2006] MySQL server has gone away  


In Connector.php line 70:

  PDO::__construct(): Error while reading greeting packet. PID=21464

i tried " php artisan clear " but i got same error .

i am trying to run this project on local . i use php 7.4 i use wamp.



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

jeudi 22 avril 2021

How to all array inputs in laravel and displaying the validation error below of the fields

My goal here is when I hit the submit button, all fields will validate and will automatically display a validation error below of each input fields, for now when I try submitting the form without putting any data to the fields, only the first input field has an error message displaying below of the input field and the other fields does not have only after I submit the form and then I click the input fields the message will show.

I tried to look the solution here but unfortunately it doesn't work for me.

I have a form that looks like this

<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div>
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div>

This is the rule/code on my request class

 'ref_name' => 'array',
 'ref_name.*' => 'required|distinct'

I'm using this https://packagist.org/packages/proengsoft/laravel-jsvalidation as my validation plugin on my laravel project.

The laravel version project im working on is 5.2



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

How to fetch data from database if one model has relation with two models in Laravel

I'm trying to fetch data from database using Laravel eloquent but it returns no data. Here is the database structure

  • Region

    • id
    • name
  • District

    • id
    • name
    • region_id
  • Ward

    • id
    • name
    • region_id

So the ward doesn't relate with district it relates with Region. How can I get ward(data)? This is how I fetch data

Region::with('district.ward')->get();

Models

Region.php

public function district()
    {
        return $this->hasMany(District::class);
    }

public function ward()
   {
    return $this->hasMany(Ward::class);
   }

District.php

public function region()
    {
        return $this->belongsTo(Region::class);
    }

Ward.php

public function regions()
    {
        return $this->belongsTo(Region::class);
    }


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

When i run commande composer require laravel/ui="1.*" --dev these error appears .I'm using laravel 5.4

Your requirements could not be resolved to an installable set of packages.

Problem 1 - laravel/ui[v1.0.0, ..., v1.3.0] require illuminate/console ~5.8|^6.0 -> found illuminate/console[v5.8.0, ..., v5.8.36, v6.0.0, ..., v6.20.24] but these were not loaded, likely because it conflicts with another require. - Root composer.json requires laravel/ui 1.* -> satisfiable by laravel/ui[v1.0.0, ..., v1.3.0].

Installation failed, reverting ./composer.json and ./composer.lock to their original content.



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

Issue with N+1 queries with accessors when using Lighthouse GraphQL and Laravel

I'm having a bit of an issue with the old N+1 problem. I'm running Lighthouse 4.8, Laravel 5.8, and have batched_queries and batchload_relations set to true in my config. I have the hasMany and hasOne set in my schema (anonymised a little):

type Team {
    id: Int!
    Y_resource_id: Int
    X_resource_id: Int
    name: String
    description: String
    start_date: Date
    cost: Float
    Y: Resource @hasOne
    X: Resource @hasOne
    members(
        where: _ @whereConditions
        hasDepartmentMember: _ @whereHasConditions(columns: ["z_id","start_date"])
        orderBy: [OrderByClause!] @orderBy
    ): [TeamMember] @hasMany @is_logged_in
    options: [TeamResourceOption] @hasMany
    optionIds: [Int!]
}

I'm using multiple accessor functions which utilise these relationships, as well as some custom resolvers and local scopes. These seem to be the ones that are causing the N+1 issues, for example when I am loading in a Team, one of the php queries that is having the N+1 issue is this (on the Team model after trying to load a team in and populate information):

public function getHasTeamLeaderAttribute(): bool
{
    return $this->members()->teamLeaders()->count() > 0;
}

this is the members() function:

public function members(): HasMany

{
    return $this->hasMany(TeamMember::class);
}

and the on the TeamMember class:

public function scopeTeamLeaders($query)
{
    return $query->where('team_members.group_role', '=', TeamMember::ROLE_TEAM_LEADER);
}

Clockwork is showing this as 2 N+1 issues (I'm calling it twice):

N+1 queries: App\Models\Teams\Team::App\Models\Teams\TeamMember loaded 4 times.
Team.php:254
N+1 queries: App\Models\Teams\Team::App\Models\Teams\TeamMember loaded 2 times.
Team.php:254

I have tried using loadMissing in the accessor to load in the teamLeaders but this seems to increase the N+1 queries, and I have also tried loading the model with $with the relationships I need, however this makes the entire application slower (I assume because it's now autoloading it in where it's not needed).

This is an inherited project, and I'm not completely au fait with GraphQL so any pointers in the right direction would be great. Thanks!



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

Laravel get paramater from url in blade

I want to write in blade second parameter of URL


I using this but it is not showing parameter in blade.

IN Route: Route::get('/{id}/policydetail/{urlNumber}','MerchantDashboardController@policydetail');

Exam Url:: http://127.0.0.1:8001/backoffice/5896/policydetail/2



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

How to implement Gate/Policy @can method in laravel blade to a view component

I had implemented a Review policy using @can method in my blade.

DisplayProduct.blade

@extends('layouts.app')
@section('content')

<display-product :product="">
</display-product>

@endsection

But now I wanted to convert my blade component to vue component, so exactly how can I implement My review policy in the vue component

DisplayProduct.vue Component Snippet

            <div class="row">
                <div class="review-content ml-3 my-3"></div>
       <!-- @can method from laravel -->
                @can('delete',$review)
                some code .........
                @endcan
            </div>


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

mercredi 21 avril 2021

Laravel + React project not working without php artisan serve command

I am working on Laravel React project on localhost when I run a command

PHP artisan serve

It is working fine on http://127.0.0.1:8000/ But when I am trying to run it without php artisan serve command and trying to access with

http://localhost/project_name

It is not working. I follow all necessary changes like

  1. Move .htaccess to root folder
  2. server.php to index.php

Not any error just blank page



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

How to export excel data in chunk using Laravel?

Excel::create($file_name, function($excel) use ($app_data,$permit_type) {
    $excel->sheet('Sheet 1', function($sheet) use ($app_data,$permit_type) {
        $sheet->loadView('/reports/_export')->with([
            'vehicle' => $app_data,
        ]);
    });
})->export();

In above code I am simply export data in excel sheet which is working fine but due to large amount of data I am unable to export. So, I want to export this data in chunks but I don't have any idea that how to setup chunk in my code? Please help me.

Thank You



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

Remove unmatched criteria records from Eloquent collection

I have some problems with Eloquent Eager Loading. I have added whereHas to remove the blog don't meet the comment criteria but the comment stills return empty array. My intention is to completely remove it from the json record.

How can I completely remove the json data chain that does not meet my condition?

My current code:

User::select("id", "name", "email")
    ->with(['blog', 'blog.author', 'blog.comments' => function ($query) {
        $query->where('comment', 'John is here');
    }, 'blog.comments.owner'])
    ->whereHas('blog.comments', function ($query) {
        $query->where('comment', 'John is Here');
    })
    ->get();

My current json output is:

{
    "id": 1,
    "name": "John Smith",
    "email": "john.smith@hotmail.com",
    "blog": [
        {
            "id": 1,
            "created_at": "2021-04-09T18:08:06.000000Z",
            "updated_at": "2021-04-09T10:33:03.000000Z",
            "title": "First Blog",
            "description": "Awesome",
            "users_id": 1,
            "cover": null,
            "author": {
                "id": 1,
                "name": "John Smith",
                "email": "john.smith@hotmail.com",
                "email_verified_at": null,
                "created_at": "2021-04-08T13:29:13.000000Z",
                "updated_at": "2021-04-08T13:29:13.000000Z",
                "role": 0
            },
            "comments": [
                {
                    "id": 1,
                    "comment": "John is here",
                    "blog_id": 1,
                    "user_id": 1,
                    "created_at": null,
                    "updated_at": null,
                    "owner": {
                        "id": 1,
                        "name": "John Smith",
                        "email": "john.smith@hotmail.com",
                        "email_verified_at": null,
                        "created_at": "2021-04-08T13:29:13.000000Z",
                        "updated_at": "2021-04-08T13:29:13.000000Z",
                        "role": 0
                    }
                }
            ]
        },
        {
            "id": 6,
            "created_at": "2021-04-12T07:41:43.000000Z",
            "updated_at": "2021-04-12T08:01:18.000000Z",
            "title": "Second Blog",
            "description": "Awesome",
            "users_id": 1,
            "cover": "images/json_1618213303.png",
            "author": {
                "id": 1,
                "name": "John Smith",
                "email": "john.smith@hotmail.com",
                "email_verified_at": null,
                "created_at": "2021-04-08T13:29:13.000000Z",
                "updated_at": "2021-04-08T13:29:13.000000Z",
                "role": 0
            },
            "comments": []
        }
    ]
}

My expected output would be:

{
    "id": 1,
    "name": "John Smith",
    "email": "john.smith@hotmail.com",
    "blog": [
        {
            "id": 1,
            "created_at": "2021-04-09T18:08:06.000000Z",
            "updated_at": "2021-04-09T10:33:03.000000Z",
            "title": "First Blog",
            "description": "Awesome",
            "users_id": 1,
            "cover": null,
            "author": {
                "id": 1,
                "name": "John Smith",
                "email": "john.smith@hotmail.com",
                "email_verified_at": null,
                "created_at": "2021-04-08T13:29:13.000000Z",
                "updated_at": "2021-04-08T13:29:13.000000Z",
                "role": 0
            },
            "comments": [
                {
                    "id": 1,
                    "comment": "John is here",
                    "blog_id": 1,
                    "user_id": 1,
                    "created_at": null,
                    "updated_at": null,
                    "owner": {
                        "id": 1,
                        "name": "John Smith",
                        "email": "john.smith@hotmail.com",
                        "email_verified_at": null,
                        "created_at": "2021-04-08T13:29:13.000000Z",
                        "updated_at": "2021-04-08T13:29:13.000000Z",
                        "role": 0
                    }
                }
            ]
        }
    ]
}


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

mardi 20 avril 2021

Problem on show numbers : Undefined property: stdClass::$contact_id

enter image description here

enter image description here

In my address book application, a contact can have one or more phone numbers. I created a contacts table and a numbers table with the contact_id field in numbers. now i want to display all numbers of each contact in my page, but i get this error. Why?



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

laravel sqlsrv db connection works but db::select not working

i want to connect database with sqlsrv, it works connection but query is not working , i tried this command

if(DB::connection()->getDatabaseName())
            {
               echo "Yes! successfully connected to the DB: " . DB::connection()->getDatabaseName();
            } else {
                echo "not connected";
            }


$loginData = DB::select("exec appLogin @userName = '".$request->email."', @password  = '".$request->password."'");
        $loginData = DB::select("select * from [User]");
        echo '<pre>';
        print_r($loginData);
        die;

for that i am getting success response for database connection, but when i tried DB:select command i am getting this error

[Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it.


    


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

Get Current date time instead of local m/c date time

I want to view date and time and i am using date carbon getdate function but i am getting local machine date and time. Suppose my local machine date is 2020-03-19 then i am getting this as output from above three functions so how can i get current time and date instead of local machine date and time.` From both three linesstrong text i am getting my local machine date and time.

date_default_timezone_set('Asia/Kolkata');
    echo date('Y-m-d');
    print_r(Carbon::now());
    echo '<br/>';
    print_r(getdate());

So how can i get current date-time according to timezone instead of local machine date time?



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

Font-awesome + core web vitals + Laravel

Pagespeed Insights is complaining about fonts loading on our website:

Preload key requests

…fontawesome-pro/webfa-brands-400.woff2?167c3d4… …fontawesome-pro/webfa-solid-900.woff2?43df9d1… …fontawesome-pro/webfa-light-300.woff2?f39d4ae…

So I looked at our app.scss and I see this:

@import '~@fortawesome/fontawesome-pro/css/all.css';

and then in the app.css it is expanded to include all of those files.

How do I tell app.scss to preload these and do I really need to load ALL of the fontawesome-pro fonts on every single page? that seems really stupid.



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

How to join Product filter query in Laravel Controller?

   $maincategory=Maincategory::find($id);
   if (isset($_GET['brands'])) {
        $brandarray = implode(",", $_GET['brands']);
        $q->whereIn('products.brand',[$brandarray]);
    }
    if (isset($_GET['discount'])) {
        $from=min($_GET['discount']);
            if(in_array("0",$request->discount) && count($request->discount)==1){
                $to='10';
            }else{
                $to='100';
            }
        $q->whereBetween('products.discount',[$from,$to]);
    }
    if (isset($_GET['sortby'])) {
        if($_GET['sortby']=='discount'){
            $q->orderBy('products.discount', 'DESC');
        }elseif($_GET['sortby']=='hightolow'){
            $q->orderBy('products.actual_price', 'DESC');
        }elseif($_GET['sortby']=='lowtohigh'){
            $q->orderBy('products.actual_price', 'ASC');
        }else{
            $q->orderBy('products.id', 'DESC');
        }
        
    }
    if (isset($_GET['minprice'])) {
        $q->whereBetween('products.actual_price',array($_GET['minprice'],$_GET['maxprice']));
    }
    if (isset($_GET['color'])) {
        $colors = implode(",", $_GET['color']);
        $q->whereIn('products.color',[$colors]);
    }
    
    $productdata= Product::leftjoin('maincategories', 'maincategories.id', '=', 'products.main_category')
    ->leftjoin('secondcategories', 'secondcategories.id', '=', 'products.second_category')
    ->leftjoin('thirdcategories', 'thirdcategories.id', '=', 'products.third_category')
    ->leftjoin('brands', 'brands.id', '=', 'products.brand')->select('products.*', 'maincategories.id as main_category_id', 'maincategories.url as main_category_url', 'maincategories.name as main_category_name', 'secondcategories.id as second_category_id', 'secondcategories.url as second_category_url', 'secondcategories.name as second_category_name', 'thirdcategories.id as third_category_id', 'thirdcategories.url as third_category_url', 'maincategories.name as third_category_name', 'brands.id as brand_id', 'brands.name as brand_name')
    ->where('products.main_category',$maincategory->id)->$q->paginate(6);

This is my method code from the controller. It gives Error: Undefined variable: q How to solve this Error with Laravel Controller? How to join Product filter query in Laravel Controller?



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

Upload Image In Laravel With jQuery AJAX

I am trying to upload photo in Laravel using jQuery AJAX. But it's always failed many times with error message

The photo must be an image. The photo must be a file of type: jpeg, png, jpg, gif, svg.

I have no idea why. What's wrong with my code below?

Controller

$validator = \Validator::make($request->all(), [
        'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);
    
    if ($files = $request->file('image')) {
            //insert new file
            $destinationPath = 'public/product_images/'; // upload path
            $image_path = date('YmdHis') . "." . $files->getClientOriginalExtension();
            $files->move($destinationPath, $image_path);
        }

        $productId = DB::table('products')->insertGetId(
            [
                'product_photo' => $image_path
            ]
        );

View

    $("#photo").fileinput({
        theme: 'fa',
        uploadUrl: '',
        uploadExtraData: function() {
            return {
                _token: $("input[name='_token']").val(),
            };
        },
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        overwriteInitial: false,
        maxFileSize: 2000,
        maxFilesNum: 5,
        slugCallback: function(filename) {
            return filename.replace('(', '_').replace(']', '_');
        }
    });
                        
    $('#saveBtnForCreate').click(function(e) {
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: "",
            method: 'post',
            enctype: 'multipart/form-data',
            cache: false,
            dataType: 'JSON',
            data: {
                photo: $('#photo').val()
            },
            success: function(result) {
                if (result.errors) {
                    $('.alert-danger').html(
                        'An error in your input!'
                    );
                    $.each(result.errors, function(key, value) {
                        $('.alert-danger').show();
                        $('.alert-danger').append('<strong><li>' + value +
                            '</li></strong>');
                    });
                } 
            }
        });
    });


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

lundi 19 avril 2021

why EB throw me Not Found The requested URL was not found on this server?

I upload the laravel project in a zip file, and the configuration software are enter image description here

the estructure of the project is enter image description here

and the endpoint home of laravel response succesfully but if i want to call the api's throw the error Not Found The requested URL was not found on this server. i dind't have this error before but one the day start with this issue.



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

Laravel 5.7 validation works still not

I have already asked question about Laravel 5.7 validation, however it still does not work quite right. the validation is not executed at all when sending the content.

 public function update(Request $request, Player $player)
    {
        if(Auth::check()){
                       
            $playerUpdate = Player::where('id', $player->id)
                                ->update([
                                       'first_name' => $request->input('fist_name'),
                                       'last_name' => $request->input('last_name')
                                ]);
 
            if($playerUpdate){
                return redirect()->route('players.show', ['player'=> $player->id])
                ->with('success' , 'player foo');
            }
            
 
        }
         
        return back()->withInput()->with('errors', 'Foo error');
        
        
        
    }

enter image description here

Thanks in advance



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

Laravel 5.7 validation makes nothing

My function works by itself but the validation is not executed. Does anyone know what I forgot to add?

This is a snippet of my code:

namespace App\Http\Controllers;

use App\Player;
use App\Tournament;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;


    public function store(Request $request)
    {
      $request->validate([
    'first_name' => 'alpha|min:2|max:30',
]);
        
        
        if(Auth::check()){
        
        
        
            $foo = Foo::create([
                'first_name' => $request->input('fist_name'),
                'last_name' => $request->input('last_name'),
            ]);
 
            if($foo){
                return redirect()->route('foo.show', ['foo'=> $foo->id])
                ->with('success' , 'Foo created!');
            }
 
        }
         
        return back()->withInput()->with('errors', 'Error when creating the foo');
    }

Thanks in advance



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

i try to show details from intermediate table through id rapport but the result is empty

public function show(RapportMP $rapportMP){
       $ligne = DB::table('ligne_rapport_m_p_s')
        ->join('rapport_m_p_s', 'ligne_rapport_m_p_s.rapportMP_id', '=', 'rapport_m_p_s.id')
        ->get()
        ->toArray();
        echo'<pre>';
        print_r($ligne) ;
       
       
}

i tried to join but nothing work the result is empty .can somoene be able to explain how can i show details of ligne_rapport through id rapport?




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

laravel manually login works, but after redirection to home page session is not working

i am using laravel version 8, i did single signon, i created EventServiceProvider , in this provide i did login by email data, i can see by Auth::check command login is working, but when it redirected to home page Auth::check doesn't work, can anyone please help me why i am getting this issue ? here i uploaded my code, can anyone please help me how to resolve this issue ?

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];
    public function boot()
    {
        try{
            Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) {
                $messageId = $event->getSaml2Auth()->getLastMessageId();
                $user = $event->getSaml2User();
                $userData = [
                    'id' => $user->getUserId(),
                    'attributes' => $user->getAttributes(),
                    'assertion' => $user->getRawSamlAssertion()
                ];
                $userInfo = User::where('email',$userData['id'])->first();
                if($userInfo) {
                    //$loggedInUser = Auth::loginUsingId($userInfo->id);
                    $loggedInUser = Auth::login($userInfo);
                }
            });
        } catch (\Throwable $e) {
            echo $e->getMessage(); die;
            report($e);
        }
    }
}


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

How to move laravel projevt from Wamp to lamp centoS 7

I need to move existing laravel 5 project to linux centos 7. I'm going to install lamp, copy source files and database backup and move them to new centos 7 server. Is there anything I should take into account? I moved a lot of pure PHP webpages but never laravel projects. Help appreciated :)



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

LARAVEL 5.5 REDIS - NOAUTH Authentication required

I have project in Laravel(5.5) with Redis (3.2.12). It's life project and everything is work properly. But when i am opened the logs file I found there some error. Any idea why I am getting it?

production.ERROR: `SELECT` failed: NOAUTH Authentication required. [tcp://127.0.0.1:6379] {"exception":"[object] (Predis\\Connection\\ConnectionException(code: 0): `SELECT` failed: NOAUTH Authentication required. [tcp://127.0.0.1:6379] at /var/www/html/AniDelivery/vendor/predis/predis/src/Connection/AbstractConnection.php:155)
[stacktrace]
#0 /var/www/html/AniDelivery/vendor/predis/predis/src/Connection/StreamConnection.php(263): Predis\\Connection\\AbstractConnection->onConnectionError('`SELECT` failed...', 0)
#1 /var/www/html/AniDelivery/vendor/predis/predis/src/Connection/AbstractConnection.php(180): Predis\\Connection\\StreamConnection->connect()
#2 /var/www/html/AniDelivery/vendor/predis/predis/src/Connection/StreamConnection.php(288): Predis\\Connection\\AbstractConnection->getResource()
#3 /var/www/html/AniDelivery/vendor/predis/predis/src/Connection/StreamConnection.php(394): Predis\\Connection\\StreamConnection->write('*2\
\
$3\
\
GET\
\
$1...')
#4 /var/www/html/AniDelivery/vendor/predis/predis/src/Connection/AbstractConnection.php(110): Predis\\Connection\\StreamConnection->writeRequest(Object(Predis\\Command\\StringGet))
#5 /var/www/html/AniDelivery/vendor/predis/predis/src/Client.php(331): Predis\\Connection\\AbstractConnection->executeCommand(Object(Predis\\Command\\StringGet))
#6 /var/www/html/AniDelivery/vendor/predis/predis/src/Client.php(314): Predis\\Client->executeCommand(Object(Predis\\Command\\StringGet))
#7 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(96): Predis\\Client->__call('get', Array)
#8 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(108): Illuminate\\Redis\\Connections\\Connection->command('get', Array)
#9 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php(140): Illuminate\\Redis\\Connections\\Connection->__call('get', Array)
#10 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(221): Illuminate\\Redis\\RedisManager->__call('get', Array)
#11 /var/www/html/AniDelivery/app/Http/Middleware/OperatorPhoneMiddleware.php(23): Illuminate\\Support\\Facades\\Facade::__callStatic('get', Array)
#12 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\OperatorPhoneMiddleware->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#13 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#14 /var/www/html/AniDelivery/app/Http/Middleware/BlockedAuth.php(34): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#15 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\BlockedAuth->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#16 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /var/www/html/AniDelivery/app/Http/Middleware/AdminLocale.php(31): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#18 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\AdminLocale->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#19 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#20 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#21 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#22 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(68): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#24 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#25 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#26 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#27 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#28 /var/www/html/AniDelivery/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))


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

How to call program classes of one project in another project

I have a project which is divided in two different larvel project. I wanted to use the programs classes of one larvel project to another and vice versa. What is the best approch to do this ? {for simplicity our project = application-a +application-b & we wanted to make call to programs of application-a from application-b and vice versa.)

The folder structure looks like

www/
├─ application-a/
│  └─ composer.json
   └─ custom-classes/
       └─ MyClassA.php
│
├─ application-b/
│  └─ composer.json
   └─ custom-classes/
          └─ MyClassB.php

Trying to call MyClassA.php from application-b/ & MyClassB.php from application-a/(Both have similar folder naming convention and namespaces). Im trying to use psr-4 but the problem is both the projects have same namespaces prefix, So how to use psr-4 in that case. Or any other beter solution.

Thanks in advance !



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

dimanche 18 avril 2021

How to fetch huge data in datatable using laravel?

views:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup ({
            headers: {
                'X-CSRF-TOKEN': $ ('meta[name="csrf-token"]').attr ('content')
            }
        });

        var postsTable = $ ('#example1').dataTable ({
            "ordering": true,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "",
                "dataType": "json",
                "type": "POST"
            },
            "columns": [
                { "data": "sn" },
                { "data": "name" },
                { "data": "username" },
                { "data": "mobile_number" },
                { "data": "designation" },
                { "data": "create_at" },
                { "data": "action" }
            ],
            stateSave: false,
        });

        $ ('.data-table-search-input-text').on ('keyup change', function () {
            var inputElement = $ (this);

            ojoDelay (function () {

                var i = inputElement.attr ('data-column');
                var v = inputElement.val ();
                postsTable.api ().columns (i).search (v).draw ();
                //usersTable.api ().ajax.reload ();
            }, 1000, this);
        });
    });  
</script>
<script>
    ojoDelay = (function () {
        var timer = 0;
        return function (callback, ms, that) {
            clearTimeout (timer);
            timer = setTimeout (callback.bind (that), ms);
        };
    }) ();
</script>

route:

Route::post('/admin/user/search', ['as' => 'admin.user.search', 'uses' => 'admin\UserController@search', 'middleware' => 'AuthPortalKas:'.serialize(['ADMIN']), 'allow' => ['ADMIN']]);

Controllers:

public function search(Request $request) 
{
    $posts = DB::table('users')
            ->select('*')
            ->leftjoin('roles', 'users.user_id', '=', 'roles.user_id')
            ->where('users.status', '!=', 'Delete')
            ->where('roles.role_id', '!=', 1)
            ->get();
    $totalData = count($posts);
    $totalFiltered = $totalData;
    $data = array();
    if(!empty($posts))
    {
        $i = 1;
        foreach ($posts as $post)
        {
            $nestedData['sn'] = $i;
            $nestedData['name'] = $post->name;
            $nestedData['username'] = $post->first_name." ".$post->last_name;
            $nestedData['mobile_number'] = $post->mobile_number;
            $nestedData['designation'] = $post->designation;
            $nestedData['create_at'] = $post->created_at;

            $buttons = '<a class="btn btn-success" href=""><i class="fa fa-search-plus"></i></a>
            <a class="btn btn-info" href=""><i class="fa fa-edit"></i></a><a class="btn btn-danger" onclick="delete_record(, )"><i class="fa fa-trash-o"></i></a>';

            $nestedData['action'] = $buttons;
            $data[] = $nestedData;
            $i++;
        }
    }

    $json_data = array(
                    "draw"            => intval($request->get('draw')),  
                    "recordsTotal"    => $totalData,  
                    "recordsFiltered" => $totalFiltered, 
                    "data"            => $data   
                );

    echo json_encode($json_data);
}

In the above question I have approx 1 million data where I want to fetch and show data in datatable but what happen here when I simply run http://localhost/project/admin/user/search then it show error. I was thinking that I have problem with my route file but I don't have any idea where am I doing wrong? Please help me to solve this.

Thank You



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

one-time API call that triggers Larvel queue, to update the single column in the blade file

I need a progress bar for the each grid column with the Values from the query, Where the tableA contains data such as Name, goal. The Value is determined from the Table C, where the col in the TableC is not NULL. All the NON- NULL fields will be counted until the Goal is achieved.

Query:

$value = SELECT count(*) FROM tableA->Name(Table C) WHERE tableB->question != null;

I have a grid columns with the static progress widget, with the mock value.

-<div class="container">
        <div class="row justify-content-center" v-for = "TableAdata in  tableA">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header"></div>

                    <div class="card-body">
                       <progress-widget>  </progress-widget>
                    </div>

                   <div class="card-goal">
                      <div>   </div> 
                    </div>
                  <div class="card-value">
                      <div>   </div> 
                    </div>
                </div>
            </div>
        </div>
    </div>

In the script

<script>
export default {

      data: function() {
            return {
               tableA:[],
               value: 30
            }
        },

    mounted() {
       this.loadContents();


    },
    methods: {
      loadContents: function() {
           //load Api
           axios.get('/api/tableA')
           .then((response) => {
               this.tableA = response.data;
             }}}

I have just mocked the value for all the goals. The value should be dynamic, based on the value the progress widget should be updated for the single card.

How can I do this? API call should be for individual project Name, each card. No bulk requests.

How can I make a controller to get the Value for each project? How to trigger a laravel queue to do a push ? Could anyone please help? Since I am new to laravel.

Thanks.



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

Laravel 5.2 - Can You Create A Relationship Between A Pivot Table And A Table It's Not Pivoting For?

I have a pivot table called user_store. It's used to establish a many to many relationship between the users table and the stores table and looks something like this:

user_id - int
store_id - int
user_age_range - string

I have another table called user_memberships. It's columns look like:

user_id - int
store_id - int
membership_cost - decimal
membership_expiration - date

I need to establish a relationship between the user_memberships table and the user_store pivot table using the user_id and store_id columns present in both tables.

How would I do this when the user_store table does not have its own model (since it's a pivot table)?



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

Duplicate a Product in Voyager Admin Panel Laravel

I'm using Voyager Admin panel for my E-commerce web application. I have many products that are similar to each other. I want to add a duplicate product button to I can just click and duplicate any item. Thanks



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

samedi 17 avril 2021

How to use "Read More" button in laravel with javascript

Hello everyone How to use Read More button With laravel and Javascript.

Laravel Code:

{!! str_limit(($activity->subject->discussion), 300, '') !!}
            @if (strlen($activity->subject->discussion) > 300)
                <span id="dots">...</span>
                <span id="more" style="display:  none;"></span>
                
            @endif

Here i think if condition also count the html tags

Javascript Code:

    <script type="text/javascript">
function myFunction() {
    var dots = document.getElementById("dots");
    var moreText = document.getElementById("more");
    var btnText = document.getElementById("myBtn");

    if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.innerHTML = "Read more";
        moreText.style.display = "none";
    } else {
        dots.style.display = "none";
        btnText.innerHTML = "Read less";
        moreText.style.display = "inline";
    }
}
</script>

using these read more button is work But when we click on any read more button every time open the first paragraph and also in if condition display "read more" button which data length is less than 300.



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

Configure database dynamically By using laravel api

Access database according to the user data in laravel API

I want to config a database connection according to users gives the host,port,databaseName,table name by these data I want to access a database in laravel.



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

am trying to save product price inside billProduct table in every bill created

how to take price column and cost price from Product table and save it to BillProducts Table when creating Bill

this is the BillProducts Model Where i need to insert price and cost price in every time i create bill

class BillProduct extends Model
{
    protected $fillable = [
        'bill_id', 'product_id', 'quantity', 'unit', 'packing', 'remark', 'discount','price','cost_price'
    ];

    protected $appends = ['price','profit'];

    public function product()
    {
        return $this->belongsTo(Product::class)->withDefault();
    }


}

also, I have a product table where I do store all products information :

class Product extends Model
{
    use Translatable;

    public $translatedAttributes = ['description', 'title'];
    public $translationModel = ProductTranslation::class;


    const FILLABLE = ['price', 'quantity', 'cost_price', 'supplier_id','item_code'];
    protected $fillable = self::FILLABLE;

    public function createTranslation(Request $request)
    {
        foreach (locales() as $key => $language) {
            foreach ($this->translatedAttributes as $attribute) {
                $this->{$attribute . ':' . $key} = $request->get($attribute . '_' . $key);
            }
            $this->save();
        }
        return $this;
    }

    public function billProduct()
    {
        return $this->hasMany(BillProduct::class);
    }
}


Now every time I choose a product when creating a bill I need to save the product price also in billProducts Table 

I need to do that to avoid changing the bill total when updating any product 

also i use this function in model to create products in billProducts


    public function createProducts(Request $request)
    {
        foreach ($this->billProducts ?? [] as $billProduct) {
            $billProduct->product->updateQuantity($billProduct->quantity);
            $billProduct->delete();
        }
        $dataArr = [
            'status' => true,
            'item' => $this
        ];

        foreach ($request->products ?? [] as $product) {
            $productObj = Product::findOrFail($product['product_id']);
            if ($productObj->updateQuantity(-1 * $product['quantity'])) {
                $product['bill_id'] = $this->id;
                BillProduct::create($product);
            } else {
                $dataArr['status'] = false;
            }
        }
        $this->save();

        return $dataArr;
    }


enter image description here



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

I want to get the students count with age break down using Laravel 7

I wrote the query to get the student's age but I want to have the breakdowns with age and the count. This is my query to getting each student's age.

$students = DB::table('students')->select(DB::raw('TIMESTAMPDIFF(YEAR, stud_dob, CURDATE())+0 AS age'))->orderBy('age')->get();

And I used one query to get the breakdowns but it's giving the wrong count for the students.

$ranges = [ // the start of each age-range.
            '18-24' => 18,
            '25-35' => 25,
            '36-45' => 36,
            '46+' => 46
        ];

$output = Student::where('stud_flag','1')
            ->get()
            ->map(function ($user) use ($ranges) {
                $age = Carbon::parse($user->stud_dob)->age;
                foreach($ranges as $key => $breakpoint)
                {
                    if ($breakpoint >= $age)
                    {
                        $user->range = $key;
                        break;
                    }
                }
                return $user;
            })
            ->mapToGroups(function ($user) {
                return [$user->range => $user];
            })
            ->map(function ($group) {
                return count($group);
            })
            ->sortKeys();

I want the output like. Please help me to fix this issue.

Range      Count 
------    --------

18 - 24     20
25 - 35     15
36 - 45     18
46+         30


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

InvalidArgumentException [closed]

C:\xampp\htdocs\perpustakaan-digital>php artisan db:seed

InvalidArgumentException : You requested 1 items, but there are only 0 items available.

at C:\xampp\htdocs\perpustakaan-digital\vendor\laravel\framework\src\Illuminate\Support\Arr.php:476 472| 473| $count = count($array); 474| 475| if ($requested > $count) {

476| throw new InvalidArgumentException( 477| "You requested {$requested} items, but there are only {$count} items available." 478| ); 479| } 480|

Exception trace:

1 Illuminate\Support\Arr::random([]) C:\xampp\htdocs\perpustakaan-digital\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1497

2 Illuminate\Support\Collection::random() C:\xampp\htdocs\perpustakaan-digital\database\factories\BukuFactory.php:18

Please use the argument -v to see more details.



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

vendredi 16 avril 2021

How to get currently inserted row id in laravel 5.5

Here I am using laravel 5.5. My code is

$result = DB::insert('INSERT INTO .......');

Here it returns true . But how can I get inserted id . In my table id is primary key . Thanks in advance



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

Trying to get property of non-object while fetching data in laravel 5.2

<?php
    if(!empty(App\Http\Models\ApplicationData::getDataCodeHtml($application_data->application_data_id)))
    {
?>
        <p>{!! App\Http\Models\ApplicationData::getDataCodeHtml($application_data->application_data_id) !!}</p>
    }
?>

In the above code I am simply fetch data from model but what happen here In some application data are showing but in somewhere it show Trying to get property of non-object. I don't know why? I simply wants if data is not present then it show empty. So, How can I do this? Please help me.

Thank You



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

Laravel application error 500 from SQLSTATE[42S22]: Column not found: 1054 Unknown column

how are you? I have a laravel application in xampp with php 7, when I want to login I get an error 500, if I check the error_log in the storage folder, I see that it is the following error:

[2021-04-16 23:36:32] live.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'username' in 'where clause' (SQL: select * from users where username = admin and users.deleted_at is null limit 1) {"exception":"[object] (Illuminate\Database\QueryException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'username' in 'where clause' (SQL: select * from users where username = admin and users.deleted_at is null limit 1) at C:\xampp\htdocs\p2\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664, PDOException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'username' in 'where clause' at C:\xampp\htdocs\p2\vendor\laravel\framework\src\Illuminate\Database\Connection.php:326) [stacktrace]

This is my first time whit laravel, I don't know how to resolve this issue, the code of the lines 326 and 664 are the next:

326) public function select($query, $bindings = [], $useReadPdo = true) { return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) { if ($this->pretending()) { return []; }

        // For select statements, we'll simply execute the query and return an array
        // of the database result set. Each element in the array will be a single
        // row from the database table, and will either be an array or objects.
        $statement = $this->prepared($this->getPdoForSelect($useReadPdo)
                          ->prepare($query));

        $this->bindValues($statement, $this->prepareBindings($bindings));

        $statement->execute();

        return $statement->fetchAll();
    });
}
  1. Is only the catch of teh error, maybe could be usefull

protected function runQueryCallback($query, $bindings, Closure $callback) {

    try {
        $result = $callback($query, $bindings);
    }

    // If an exception occurs when attempting to run a query, we'll format the error
    // message to include the bindings with SQL, which will make this exception a
    // lot more helpful to the developer instead of just the database's errors.
    catch (Exception $e) {
        throw new QueryException(
            $query, $this->prepareBindings($bindings), $e
        );
    }

I received this application from a company that has me as an intern, but they didn't give me any more help or guidance, they just want it to work. I appreciate any comments that can help me solve it.



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

Validation closure not firing?

I want to create a custom validation using closures in Laravel 5.6 as explained in the docs: https://laravel.com/docs/5.6/validation#using-closures

That is my code:

   public function store(Request $request)
    {
        \Illuminate\Support\Facades\Validator::make($request->all(), [
            'trainer' => [
                function ($attribute, $value, $fail) {
                    return $fail($attribute . ' is invalid.');
                },
            ],
        ]);

        if ($validator->fails()) {
          dd($validator->messages());
        }

        dd('NO ERROR??');
   }

Testing it using

$this->post('/my_test_route', []);

Returns

NO ERROR??

Why is this? If I change the code to

   public function store(Request $request)
   {
        Illuminate\Support\Facades\Validator::make($request->all(), [
            'trainer' => 'required',
        ]);

        dd('NO ERROR??');
   }

I get as expected:

Illuminate\Support\MessageBag^ {#2408
  #messages: array:1 [
    "trainer" => array:1 [
      0 => "The trainer field is required."
    ]
  ]
  #format: ":message"
}

What am I missing?



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

Laravel optimize query

In my Database i hv column name type which contains the value Ship and Ship+ and status from 1 to 15 So if the value is Ship and check status value more than 8 and less than 13 if the value is Ship+ and check status value more than 8 and less than 15...So here how can i modify the below query to reduce the exection time.

    $start_time = microtime(true);
    CS::where('status','>', 8)->chunkById(100, function ($items) use (&$post) {
    foreach ($items as $item){
            $item= CS::where('awb', $item->awb)->first();

           
                $this->info('Status ' . $item->delivery);
                $this->info('Country` ' . $item->country_code);
      }
    });
    $end_time = microtime(true);
    $execution_time = ($end_time - $start_time);
    Log::info("total execution time=".'  '.$execution_time);


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

jeudi 15 avril 2021

Laravel - RetaurantLoginController Exist But Error Show Restaurant Login Controller Does Not Exist

enter image description here

Controller does not exist error



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

How should the Laravel query builder output of this query be?

How should the Laravel query builder output of this query be?

 Select T.price_default,price_discounted,price_date,room.hotel_room_id,hotel_lang.title,hotel_lang.description,hotel_lang.slug,hotel_lang.lang_code,hotel.showcase_image,hotel.address,hotel.hotel_id from (Select *,ROW_NUMBER() OVER (
                 PARTITION BY hotel_room_id
                 ORDER BY price_date ASC
           ) AS ROWNUMBER from hotel_room_prices Where price_date BETWEEN '$mindate' AND '$maxdate' ) AS T
                    left join hotel_rooms room on T.hotel_room_id=room.hotel_room_id
                    left join hotels hotel on room.hotel_id=hotel.hotel_id
                    left join hotel_langs hotel_lang on hotel.hotel_id=hotel_lang.hotel_id
                        WHERE T.ROWNUMBER=1 and hotel_lang.lang_code='$locale' and t.price_default >= $min_price and t.price_default <= $max_price and hotel_lang.title ILIKE '%$query%'


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