lundi 29 novembre 2021

Is it possible to copy file directly from sign url fetch from amazon S3?

I have fetch url from AWS Bucket like this: https://{bucket_path}/iportalDocuments/99/aid.jpeg?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIARYDJGMIUARGRF2Y3%2F20211130%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20211130T065101Z&X-Amz-SignedHeaders=host&X-Amz-Expires=1200&X-Amz-Signature=f2e7ccba4e7d42238d03c311cc0fb9768fb47b52891d8cbe86def3f4f827762e

Is it possible to copy file from url using spatie library. Thank you in advance..



via Chebli Mohamed

Calling the failed function: 'should not be called statically' in laravel 5.4

I use version laravel 5.4

In Helpers/Helper.php

public function test()
{
  return 'success';
}

In controller

use App\Helpers\Helper;

public function index()
{
  $val = Helper::test();
  dd($val);
}

Error : Helper::test() should not be called statically

I called the function inside helper to use it. But got the error as above. Please show me how to get the function in helper. Thank you



via Chebli Mohamed

Laravel complex relationship many to many

I’m building a app in laravel and now I’m doing a payments resource.

The ideia is select many orders in the list to receive in same time. And in this receives can be used many type of payment (money, credit).

Now I has this tables order(id, total), paymentTypes(id, paymentName), payments(id, payment_type_id, value) and order_payments(order_id, payment_id).

This structure is more adequate to this situation? And how can I get orders with all payments and the other orders payed together?

Any help is important.

Thanks everyone .



via Chebli Mohamed

Laravel 5.8 stopped sending email

Sending emails from my system has stopped working at all. .env settings are ok. I tried to run this code to test:

php artisan tinker

Mail::getSwiftMailer()->registerPlugin (
    new Swift_Plugins_LoggerPlugin(new Swift_Plugins_Loggers_EchoLogger(false))
);
$to = 'youraddress@example.com';
Mail::raw('Testmail', function ($message) use($to) {  
    $message->to($to)->subject('Testmail'); 
});

and I'm getting this error:

PHP Warning:  stream_socket_client(): php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution in /home/usuario/dev/dev-contaja/vendor/predis/predis/src/Connection/StreamConnection.php on line 127
PHP Warning:  stream_socket_client(): unable to connect to tcp://redis:6379 (php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution) in /home/usuario/dev/dev-contaja/vendor/predis/predis/src/Connection/StreamConnection.php on line 127
Predis/Connection/ConnectionException with message 'php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution [tcp://redis:6379]'

I'm using use docker.



via Chebli Mohamed

AJAX json response data undefined in Laravel 5.7

I have to get response data from API I have succeeded in response but when I am getting one response of data then I have got an undefined error. I am trying to get an error message from API on button click event or display the alert message of API error response of data.

Controller :

 public function apiStatus(Request $request)
{

    $to =  $this->shop->api_test_phone;

    $curl = curl_init();
    $response = my_api;

    curl_setopt($curl, CURLOPT_URL, $response);
    curl_exec($curl);

    $response = json_encode($response);
    curl_close($curl);
    return $response;
}

Blade file:

<script type="text/javascript">
$(document).on('click','#checkApi',function(){
    startAjaxLoading();
    $.ajax({
            type: "GET",
            cache: false,
            url: "",
            success: function (response) 
            {
                console.log(response);
            
                if (response == true) 
                { 
                    var msg = response.message;
                    console.log(msg);
                    notie.alert({text: msg });
                    stopAjaxLoading();
                }
                else
                {
                    var msg = response.message;
                    console.log(msg);
                    notie.alert({ text: msg });
                    stopAjaxLoading();
                }
            }     
        });
    });


via Chebli Mohamed

dimanche 28 novembre 2021

Adding validation if another validation passed in laravel FormRequest

Is it possible to add validation if another validation passed for example I have the following validation rules

return [
            'name' => ['required', 'string', 'min:3', 'max:30'],
            'password' => ['required', 'min:6'],
            'photo' => ['imageable'],
            'business_uuid' => ['required', 'uuid', 'exists:businesses,uuid'],
        ];

and I would like if the business_uuid validation passed to add validation for the phone number

'phone' => ['nullable', 'phone:'.$countryCode],

notice that I'm the country code will be brought from the business That's why I'm I'd like to add it if the validation passed



via Chebli Mohamed

vendredi 26 novembre 2021

real-time data finder - search with multiple models

i need to make my search engine work with multiple data tables

right now get data from the model "Registro".

    public function buscador(){
        
        return view('posts.index');
        
    }
        public function search(Request $request){
            
            $results = Registro::where('cliente', 'LIKE', "%{$request->search}%")->get();
            
            return view('posts.results', compact('results'))->with(['search' => $request->search])->render();
            
        }
        public function show(Request $request){
            
            $post = Registro::findOrFail($request->id);
            return view('posts.post', compact('post'))->render();
            
       
    
}

can search with multiple models?



via Chebli Mohamed

jeudi 25 novembre 2021

Laravel in my Multiple Attribute functionality is not proper working it can't increase the array size

Please tell me the error when I add multi attribute (array) of member it take only first of arrray[0] and does not increases index number Please tell in where I problem in this code. Does anyone know the problem here:

It is controller code functionality manage_members_list:

public function manage_members_list($id=''){

    if ($id > 0) {
        $arr = Members_list::where(['id' => $id])->get();
        $result['id'] = $arr[0]->id;
        $result['name'] = $arr['0']->name;
        $result['father_name'] = $arr['0']->father_name;
        $result['email'] = $arr['0']->email;
        $result['mobile'] = $arr['0']->mobile;
        $result['phone'] = $arr['0']->phone;
        $result['cnic'] = $arr['0']->cnic;
        $result['city'] = $arr['0']->city;
        $result['area'] = $arr['0']->area;
        $result["member_gruntee"] = Garuanter::where(['member_id' => $id])->get();

    } else {
        $result['name'] = '';
        $result['father_name'] = '';
        $result['email'] = '';
        $result['mobile'] = '';
        $result['phone'] = '';
        $result['cnic'] = '';
        $result['id'] = 0;
        $result['city'] = '';
        $result['area'] = '';

        $result['member_gruntee'][0]['id'] = 0;
        $result['member_gruntee'][0]['gname'] = '';
        $result['member_gruntee'][0]['gaddress'] = '';
        $result['member_gruntee'][0]['gcnic'] = '';
        $result['member_gruntee'][0]['gphone'] = '';

 
    }
    $result['city_list'] = City::all();
    return view('manage_members_list', $result);
}

if you understand this problem then ok, otherwise I'll send you more code



via Chebli Mohamed

Unable to apply constraints/foreign in Laravel 5.3 Migrations

I'm contacting you because I absolutely can't find the solution after having spent a lot of time on it...

Here is my problem:

I naturally created my tables on Laravel 5.3 (resumption of a project) for the arrival of a new feature.

After setting up everything, Model/ Controller/CRUD I noticed a problem with the ORM. When I go to create the table with its constraints, foreign keys through the orm. It doesn't apply it fully. That is, it will define the key as an index but it will not create the constraint... I tried to use a DB::statement but it gives the same result.

I tried to update doctrine/dblab but it didn't work. Do you think the MySQL version could be the cause? Something wrong with the settings? Knowing that the previous migrations the constraints are present!

Thanks in advance to those who will help me!

Look : Img : Viewpoint on HeidiSQL

Application Types :

Schema::create('application_types', function (Blueprint $table) {
           
            //Ids
            $table->increments('id');

            // details
            $table->char('type', 50)->unique();

            // dates
            $table->timestamp('created_at')->useCurrent(); // useCurrent equals to -> default(DB::raw('CURRENT_TIMESTAMP'))
            $table->timestamp('updated_at')->nullable()->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
        });

Aplication Categories :

Schema::create('application_categories', function (Blueprint $table) {
           
            //Ids
            $table->increments('id');

            // details
            $table->char('name', 50)->unique();

            // dates
            $table->timestamp('created_at')->useCurrent(); // useCurrent equals to -> default(DB::raw('CURRENT_TIMESTAMP'))
            $table->timestamp('updated_at')->nullable()->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
        });

Applications :

Schema::create('applications', function (Blueprint $table) {
           
            //Ids
            $table->increments('id', true);
            $table->integer('type_id')->unsigned(); // -> link to application types table
            $table->integer('document_id')->unsigned(); // -> link to documents table
            $table->integer('category_id')->unsigned(); // -> link to application category table
            $table->integer('referent_id')->unsigned(); // -> link to dir_people table
            $table->integer('created_by_user_id')->unsigned(); // -> link to users table
            $table->integer('updated_by_user_id')->unsigned()->nullable(); // -> link to users table


            // details
            $table->char('name', 50);
            $table->longtext('description');
            $table->longtext('path');
            $table->boolean('is_active')->default(1);

            // dates
            $table->timestamp('created_at')->useCurrent(); // useCurrent equals to -> default(DB::raw('CURRENT_TIMESTAMP'))
            $table->timestamp('updated_at')->nullable()->default(DB::raw('null ON UPDATE CURRENT_TIMESTAMP'));      
      });

// == Set foreign keys == 
Schema::table('applications', function (Blueprint $table) {
            
            //Document
            $table->unique('document_id');

            $table->foreign('document_id')
                  ->references('id')->on('documents')
                  ->onDelete('cascade');

            // Application type
            $table->foreign('type_id')
                  ->references('id')->on('application_types');

            // Application Category
            $table->foreign('category_id')
            ->references('id')->on('application_categories');

            // Referent_id
            $table->foreign('referent_id')
                  ->references('id')->on('dir_people');
            
            // Created by User
            $table->foreign('created_by_user_id')
                  ->references('id')->on('users');
            
            // Updated by User
            $table->foreign('updated_by_user_id')
                  ->references('id')->on('users');
      });      


via Chebli Mohamed

Why does toggle inside modal won't work in laravel?

Hi I'm currently working on a toggle(active - inactive) inside a modal. I was able to make it work, changing active to inactive. However, turning it back to active won't work and status stays inactive.

How can I make this work? What's missing here?

Thanks in advance

images html toggle button

datatable

Here's my JS

$("#updatetaxform").on('submit', function (e) {
e.preventDefault() 
const pid = $("#updatetaxform [name=pid]").val();
const IsActive = $("#updatetaxform").prop('checked') == true ? 1 : 0;
$.ajax({
    data: {
        pid,
        IsActive
    },
    url: "/edit-tax",
    type: "POST",
    success: function (data) {
        console.log(data.success) 
        var oTable = $('#tax-info-table').dataTable()
        oTable.fnDraw(false)
        Swal({
            type: 'success',
            title: 'Success!',
            text: "Successfully updated!",
            showConfirmButton: false,
            timer: 3000
        }).then(function () {
            location.reload()
        })
       
    },
    error: function (data) {
        console.log('Error:', data.responseJSON.message);
        Swal({
            type: 'error',
            title: 'Tax Information Error',
            text: data.responseJSON.message
        })
    }
}) })

Here's my input html

<div class="form-group">
        <label for="">Active Status</label>
        <input type="checkbox" data-toggle="toggle" data-onstyle="success" data-offstyle="danger" data-style="ios slow" data-width="100" data-height="20" name="IsActive" >
      </div>

Here's my controller

public function editTax(Request $request)
{
$tax = TaxDetails::where('id', $request->id)->update(
            ['pid' => $request->pid, 'IsActive' => $request->IsActive ]
            );}

public function index()
{
  $tax1 = TaxDetails::where('pid', Session::get('pid'))->first();
  return view('pages.tax-information', [
        'taxstatus' => $tax1
        
    ]);
}


via Chebli Mohamed

mercredi 24 novembre 2021

Multi attribute of products (guaranteree table) in Laravel in which not created multiple index (array)

Please tell me error when I add multi attribute (array) of member it take only first of arrray[0] and not increases index number Please tell in where I problem in this code. Anyone know the problem?

It is controller code manage_members_list:

public function manage_members_list($id='')
{
    if ($id > 0) {
        $arr = Members_list::where(['id' => $id])->get();
        $result['id'] = $arr[0]->id;
        $result['name'] = $arr['0']->name;
        $result['father_name'] = $arr['0']->father_name;
        $result['email'] = $arr['0']->email;
        $result['mobile'] = $arr['0']->mobile;
        $result['phone'] = $arr['0']->phone;
        $result['cnic'] = $arr['0']->cnic;
        $result['city'] = $arr['0']->city;
        $result['area'] = $arr['0']->area;
        $result["member_gruntee"] = Garuanter::where(['member_id' => $id])->get();

    } else {
        $result['name'] = '';
        $result['father_name'] = '';
        $result['email'] = '';
        $result['mobile'] = '';
        $result['phone'] = '';
        $result['cnic'] = '';
        $result['id'] = 0;
        $result['city'] = '';
        $result['area'] = '';

        $result['member_gruntee'][0]['id'] = 0;
        $result['member_gruntee'][0]['gname'] = '';
        $result['member_gruntee'][0]['gaddress'] = '';
        $result['member_gruntee'][0]['gcnic'] = '';
        $result['member_gruntee'][0]['gphone'] = '';
    }
    $result['city_list'] = City::all();
    return view('manage_members_list', $result);
}

Blade Template Data is here:

<div class="row" style="margin-top: 10px;">
            <div class="col-sm-12 right_contents content_right">
                <div class="inner_contents table-responsive customers_setup">
                    <div class="main_head">
                        <h4>Gauranters</h4>
                    </div>

                        @php
                            $loop_count_num = 1;
                            $loop_count_prev = $loop_count_num;
                        @endphp
                        @foreach ($member_gruntee as $key)
                            @php
                                $loop_count_prev = $loop_count_num;
                            @endphp
                            <div class="member_gruantee">
                            <input type="hidden" id="mmd" name="mmd[]" value="">
                            <div class="form-group">
                                <div id="member_attr_">

                                <div class="row">

                                    <div class="col-sm-2 padd_right">
                                        <div class="input_label_box">
                                            <label>Name*</label>
                                            <input type="text" placeholder="" id="gname" name="gname[]"
                                                value="">
                                        </div>
                                    </div>
                                    <div class="col-sm-2 padd_right">
                                        <div class="input_label_box">
                                            <label>Phone</label>
                                            <input type="text" id="gphone" placeholder="" name="gphone[]"
                                                value="">
                                        </div>
                                    </div>
                                    <div class="col-sm-2 padd_right">
                                        <div class="input_label_box">
                                            <label>CNIC</label>
                                            <input type="text" id="gcnic" name="gcnic[]" value="">
                                        </div>
                                    </div>
                                    <div class="col-sm-5">
                                        <div class="input_label_box">
                                            <label>Address</label>
                                            <input type="text" id="gaddress" name="gaddress[]" value="">
                                        </div>
                                    </div>
                                    @if ($loop_count_num == 2)
                                        <div class="col-sm-1">
                                            <div class="plus_btn">
                                                <a type="submit" onclick="add_more()" id="Add"><i
                                                        class="fa fa-plus"></i></a>
                                            </div>
                                        </div>
                                    @else
                                        <div class="col-sm-1">
                                            <div class="minus_btn">
                                                <a href="//"
                                                    onclick="remove_more('')" id="Remove"><i
                                                        class="fa fa-minus"></i></a>
                                            </div>
                                        </div>
                                    @endif
                                </div>
                        @endforeach
                    </div>
                </div>
               </div>
            </div>

    

JQuery Function is here:

var loop_count = 1;

function add_more() {
    loop_count++;
    var html =
        '<input type="hidden" id="mmd" name="mmd[]"><div class="form-group"><div id="member_attr_'+loop_count +'"><div class="row">';
    html +=
        '<div class="col-sm-2 padd_right"><div class="input_label_box"><label>Name*</label><input type="text" name="gname[]" id="gname" placeholder="" ></div></div>';
    html +=
        '<div class="col-sm-2 padd_right"><div class="input_label_box"><label>Phone</label><input type="text" name="gphone[]" id="gphone" placeholder=""></div></div>';
    html +=
        '<div class="col-sm-2 padd_right"><div class="input_label_box"><label>CNIC</label><input type="text" name="gcnic[]" id="gcnic"></div></div>';
    html +=
        '<div class="col-sm-5"><div class="input_label_box"><label>Address</label><input type="text" id="gcnic" name="gaddress[]"></div></div>';
    html += '<div class="col-sm-1"><div class="minus_btn"><a onclick=remove_more("' + loop_count +
        '") id="Remove"><i class="fa fa-minus"></i></a></div></div></div></div></div>';
         $('.member_gruantee').append(html);
}


via Chebli Mohamed

Laravel eloquent call realtionship based on a boolean parameter

I'm trying to make a method to retrieve model with a relationship I'd like to be able to fetch the relation based on a boolean parameter for example, I can do it using the if condition like the following

if($load == true){
   $users = User::with('login')->all()->paginate();
}else{
$users = User::all()->paginate();
}

I'm wondering if there's a way to do it without the if condition on the fly



via Chebli Mohamed

How to get ID from react Route

I want to get the "BusinessId" of this URL

    
       <Route path={[
              `${match.url}/Business/:BusinessId/` 
              

            ]}>
               <Change/>

      </Route>

But the methods I am getting here and on other websites aren't helping me that much, I cant use components or anything with this kind of route path declaration (sorry, I am new to react and Laravel) and the thing is that the "id" comes from my "Change" class.

My "Change" class is like this:

  const [showModal, setShowModal] = useState(false);
  const [business, setBusiness] = useState();
  const { authUser } = useContext(AuthUserContext);
  const { businessId } = useParams();
  const history = useHistory();

  useEffect(useCallback(() => {
    const [run] = authUser.role === "client" ? API.get(`users/${authUser.id}/business`) : API.get("business");
    run().then((response) => {
      setNegocios(response);
      const DEFAULT_ROUTE = `/projection/business/${response[0].id}`;

      validateRoute(response, businessId, () => {
        history.push(DEFAULT_ROUTE);
      });
    });
  }, [authUser, history, businessId]), [businessId]);


  function handleCloseModal() {
    setShowModal(false);
  }
  function handleShowModal() {
    setShowModal(true);
  }
  function handleSelection(mappedBusiness) {
    history.push(`/projection/business/${mappedBusiness.id}`);
    handleCloseModal();
  }

  function getName() {
    if (business) {
      const business = business.find((businessF) => businessF.id === parseInt(businessId, 10));
      return business ? business.name : "";
    }
    return "";
  }

  return (

      <div className="content">
        <wrap>
          <h3 className="empresa">{getName()}</h3>
        </wrap>
        <button className="alterar pt-3" onClick={handleShowModal}>Change <i className="fas fa-exchange-alt"/></button>
        <Modal className="ChangeBusinessModal" show={showModal} onHide={handleCloseModal}>
          <Modal.Header closeButton>
            <Modal.Title></Modal.Title>
          </Modal.Header>
          <Modal.Body>
            {business &&
           business.map((mappedBusiness) => (
             <button
               key={mappedBusiness.id}
               onClick={handleSelection.bind(null, mappedBusiness)}
               className="button-business">
               {mappedBusiness.name}
             </button>))
            }
          </Modal.Body>
        </Modal>
      </div>
  );

}
export default Change;

The thing is, there's a way I can get the ID that comes from the Change modal to the route Id I have in the other class? And how?

Once again, sorry if it's kind of dumb, but I am new to this



via Chebli Mohamed

Change table name not working with another database connection

I created a Model with another connection string and change table name to answer_sheet_omr.

{
    //protected $table='answer_sheet_omr';
    protected $connection = 'mysql2';
    protected $table='answer_sheet_omr';

} 

But after that show the following error SQLSTATE[42S02]: Base table or view not found: 1146 Table 'hmsprawq_hmspro.answer_sheet_omr'

hmsprawq_hmspro is my default database not in mysql2 database connection.

I need an help to change table name with another database connection.



via Chebli Mohamed

After migrating with laravelshift from 5.8 to 6.2, receiving Sessions Permission denied error

I've updated my laravel project from version 5.8 to 6.2 using laravelshift. Done running composer update command. getting "file_put_contents(/var/www/app.buyonecollective.com/public_html/storage/framework/sessions/Nu5bUgYOijmGdD6f2GyHjNci7xMcO7rsE0D4jSk3): failed to open stream: Permission denied " Reference SS. Tried running:

1. php artisan config:clear
2. php artisan cache:clear
3. php artisan config:cache

But couldn't get any luck. Any help would be appreciated. Thanks in advance.



via Chebli Mohamed

how many api's and routes we need for app like this [closed]

The customer determines the shipment and sends the order data and location to the nearest drivers. Then each driver sets the delivery price for the order, the prices are shown to the customer, and he accepts one of these orders i want to knwo how many api's and routes we need to build to finish this feature



via Chebli Mohamed

mardi 23 novembre 2021

How can I paginate the data from a Stored procedure using the paginate function in Laravel?

It's a requeriment to use store procedures it's for a homework and for that I'm using a Laravel 8 and MySql. My store procedure is the next one:

CREATE PROCEDURE sp_obtener_entradas()
BEGIN
    SELECT * FROM vale_de_entrada
    WHERE Activo = 1 ORDER BY ID_vale_entrada DESC;
END


via Chebli Mohamed

Laravel - calculate total amount according to json array

I have Below Types Of Dynamic Json array, Now I want to create an amount based on channel like,

if I have channel 300 then it's 300*1 = 300

if channel 600 then its amount = (399 *1) + ((600-399) * 2)

if channel 1000 then amount should be = (399 *1) + ((700-399) * 2) + ((1000-700) * 3)

First, find a channel between which array row and then multiply by amount field.

[
  {
    "id": 1,
    "name": "tier1",
    "from": 1,
    "to": 399,
    "amount": 1,
    "channel_type": 1,
    "status": 1
  },
  {
    "id": 2,
    "name": "tier2",
    "from": 400,
    "to": 700,
    "amount": 2,
    "channel_type": 1,
    "status": 1
  },
  {
    "id": 3,
    "name": "tier3",
    "from": 701,
    "to": 1000,
    "amount": 3,
    "channel_type": 1,
    "status": 1
  }
]

Please suggest me smallest solution to this question, because I am processing by hard code, provide me with an easy and clean solution.

Thank you in advance and sorry for my poor English.



via Chebli Mohamed

lundi 22 novembre 2021

Expected status code 200 but received 500. Failed asserting that false is true. in Laravel 5.5

I always get the error 500 while it is status 200 in the browse. I have already checked on the other answers but there is no solution.

here is the code in UserTest

<?php

namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class UserTest extends TestCase
{
/**
 * A basic test example.
 *
 * @return void
 */
    public function testExample()
    {
        $this->assertTrue(true);
        //$this->withoutExceptionHandling();
        $response = $this->get('/');
        $response->assertStatus(200);
    }

}

here is the result of the test

PHPUnit 9.5.10 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 00:02.105, Memory: 22.00 MB

There was 1 failure:

1) Tests\Feature\UserTest::testExample
Expected status code 200 but received 500.
Failed asserting that false is true.

var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:78
/var/www/laravel/tests/Feature/UserTest.php:22

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

Thank you in advance for your answer, even the few clues



via Chebli Mohamed

Laravel Roles and permission manipulation

I had a long read and application of the Laravel roles and permissions and was wondering if it's possible to remove the roles layer and directly assign permissions to users.

eg. instead of creating a role that has several permissions, roles_has_permissions, I could create users that has permission, user_has_permission.

In theory, it makes sense but in implementation, I am concerned with the fact that we are removing a layer that is an integral part of the said library. I couldn't find much information about such manipulation and I would really like some input and opinion on the matter.



via Chebli Mohamed

Search Multiple ID's with Multiple Rows by Eloquent

I have one table which is used to get data combination of input data.like multiple molecule(chemical combination) as one combination.

Input

$id = $required->input('search'); // array:2 [ 0 => "3" 1 => "8"]

Table 1

id refid product_id name ref_2
1 1,3,46,7 5 test 6
2 1,3,8,90 10 test1 8
3 3,8,67 14 test 4 11
4 8,699, 14 test 4 11

query

$molecule =Molecule::whereIn('ref_id',$id)->pluck('product_id');

Fetch Product, query of combination contains id's 3,8

but it is fetching id's contains 3 and 8

Is this possible to do and is there a better method of doing this?



via Chebli Mohamed

dimanche 21 novembre 2021

v-if condition get error message in vue.js file

working with Laravel + Vue Project. and I have following code segments in the mainapp.vue file

<div class="_1side_menu_list">
            <ul class="_1side_menu_list_ul">
              <li v-for="(menuItem, i) in permission" :key="i" v-if="permission.length && menuItem.read">
                <router-link :to="'/'+menuItem.name"><Icon type="ios-speedometer" /> </router-link>
              </li>
              <li><a href="/logout"><Icon type="ios-speedometer" /> Logout</a></li>
            </ul>
          </div>
        </div>
      </div>

but in the following line v-if="permission.length && menuItem.read" highlighting in the id and display following error message [vue/no-use-v-if-with-v-for] | The 'permission' variable inside 'v-for' directive should be replaced with a computed property that returns filtered array instead. You should not mix 'v-for' with 'v-if'.

how could I fix this problem?



via Chebli Mohamed

vendredi 19 novembre 2021

Is mass assignment protection needed when properly using validation?

I've been using Laravel (5.4) and PHP both for the very first time in a legacy app I've been tasked to maintain, and over the past couple of months I have noticed a pain point, which is mass assignment.

I believe I have a well-enough grasp of what is is, but I am not sure if I am really utilizing it correctly. The official documentation illustrates the problem using a (good, but extreme) example of a user's role. I understand the significance of this and why I should guard such variables. However, I don't think I really have a solid understanding of determining what fields to guard or not (if at all), in general.

It seems that a lot of the nice features of Laravel don't seem to have mass-assignment in mind, which is the main source of my frustration. For example, if I had an endpoint that had some optional fields (i.e. you could just not specify them in the request), then doing a mymodel->update(request->all()) would only update the fields that you provided. If many of the fields were guarded, I would have to have many repeated isset() checks if I wanted to achieve the same behaviour, which seems unnecessary. I also know that request->all() shouldn't really be used like this, but I am just trying to illustrate a point.

It becomes more cumbersome when you consider that you're probably going to use robust validation alongside something like request->only([...]) to make sure your data is correct and filtered to only what you expect.

So ultimately what I am asking is:

In the presence of robust validation and input-shaping methods, is mass-assigning nearly anything still worth doing? In general it seems that I am jumping through so many more hoops for no reason, when it seems that my validation steps already took care of the problem. If it is still worth doing, what am I missing? Should mass-assignment protection only be delegated to super-important fields, like a user's role, and nothing else?



via Chebli Mohamed

jeudi 18 novembre 2021

why do I get this message about DisabledForUser Please make sure that the app id is set correctly is it serious?

I'm getting this message when i run npm run dev or watch and I'm worried about this Reason: DisabledForUser Please make sure that the app id is set correctly.

I have imported javascript and css in the app.blade.php. Next, in the home.blade.php I'm using a div id="app" and I'm using inside the vue component called client.vue

@extends('layouts.app')

@section('content')

<div id="app">

<cliente></cliente>

</div>


@endsection
<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="">Home</a>
                    @else
                        <a href="">Login</a>

                        @if (Route::has('register'))
                            <a href="">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="https://laravel.com/docs">Docs</a>
                    <a href="https://laracasts.com">Laracasts</a>
                    <a href="https://laravel-news.com">News</a>
                    <a href="https://blog.laravel.com">Blog</a>
                    <a href="https://nova.laravel.com">Nova</a>
                    <a href="https://forge.laravel.com">Forge</a>
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
</html>


via Chebli Mohamed

how to install freelancer login page in laravel project.?

How to install freelancer login page in laravel project. I am new to laravel. I installed admin panel using some commands. But i don't know install freelancer login page.



via Chebli Mohamed

Issue saving strings on Laravel

I'm having issues storing text on Laravel. I'm trying to store product names but some characters (I only found one but I guess there's more) are not being properly stored on database so when are retrieved are not shown correctly.

This is what made me notice:

Table <0,5

It should say:

Table < 0,5

I've noticed that on the database it's stored as Table &lt;0,5 but on some sections of the web it's shown correctly (?). My idea is that in any case it should be stored as Table < 0,5.

The column type on the database it's defined as varchar(191) utf8_unicode_ci.

I don't think it's a utf-8 issue as the main language is spanish and we are working with accents with no issues.

It's Laravel 5.7 (I know it's old, we are working on ridding off)

This is how I'm storing the new products:

public function store(Request $request)
   {
    // Some validations

    $product = new Product;
    
    ...

    $product->name = $request->name;

    $product->save();
 }


via Chebli Mohamed

I want to remove id from URL in my laravel

In my Laravel application, I have created url: like "https://ift.tt/3wVw4dz" but here, I want to remove id from the last and concatenate id with my 2nd parameter that is, "property for rent" like : "https://ift.tt/3oENQOn".

In the Controller function get 3 parameters

public function single_properties(Request $request, $property_purpose, $slug, $id)

In the Blade file


In the Web.php File

Route::get('{property_purpose}/{slug}/{id}', 'PropertiesController@single_properties');

I have tried to reduce parameter from the function, blade and route, but didn't work for me. can anyone please help me out, I am poorly trapped in it,



via Chebli Mohamed

How can I convert RAW query into Laravel Eloquent way

I have this raw query, But I am not able to convert into Laravel Eloquent

Plain Raw Query:

 select * from 
     (select ci.list_id, count(ci.id) as invalid_items_count from dgo_curated_list_items ci, 
      dgo_video_post_ext v, dgo_shows s
      where ci.object_id = v.ID and v.`show_id` = s.id
      and type = 'video'
      and (v.post_status = 'draft' 
      or v.`license_from_date` > now() 
      or v.`license_to_date` < now()
      or s.`status` = 0)
      group by ci.list_id) a,
   (select i.list_id, count(i.id) as origin_items_count from 
       dgo_curated_list_items i 
       group by i.list_id) b where a.list_id = b.list_id and invalid_items_count = origin_items_count;


via Chebli Mohamed

mercredi 17 novembre 2021

CORS middleware not working on routeMiddleware array Laravel

I have this kernel.php file where \App\Http\Middleware\CORS::class, is defined in $middleware array but i cannot define this middleware in routemiddleware. This code is working but getting cors error when i put this middleware in route middleware or api middleware groups. I want to know whether i'm doing this code correctly or not.

Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\CORS::class,
        \App\Http\Middleware\TrustProxies::class,
        //\Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

api.php

Route::group(['middleware' => ['api'],'prefix' => 'auth'], function ($router) {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);   
});


via Chebli Mohamed

Server error 500 when trying to upload file on laravel application hosted on digital ocean

I am facing an issue when I try to upload this excel file that gets processed and stored in the database. On my localhost this is working so I can upload the file and using laravel-excel, it is being saved in the database.

However, on the same laravel app hosted on digital ocean, I am always getting 500 Internal server errors when I try to submit the file, Can somebody help?

enter image description here



via Chebli Mohamed

Getting Cors error in Laravel on some system

I hosted laravel (Laravel Framework 8.68.0) and angular application on two different domains, Sometime the same code works properly but sometimes it is throwing this error :

Access to XMLHttpRequest at from origin has been blocked by CORS policy Response to preflight request does'nt pass access control check : No Access Control Allow Origin header is present on the requested resource

Cors Middleware :

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*')->header('Access-Control-Allow-Headers', 'Content-type, X-Auth-Token, Authorization, Origin');
        return $response;
    }
}

Kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'cors' => \App\Http\Middleware\CORS::class,
    ];
}

api.php

Route::group(['middleware' => ['api','cors'],'prefix' => 'auth'], function ($router) {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::post('/refresh', [AuthController::class, 'refresh']);
    Route::get('/user-profile', [AuthController::class, 'userProfile']);    
});

cors.php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

Any solution is highly appreciated

Thanks.



via Chebli Mohamed

How to call a Request function from a controller to another controller in Laravel

How to call a Request function from a controller to another controller in Laravel

Controller1.php

public function get(){

$call = new Controller2();

$input = new Request();
$input->param1 = param1;
$input->param2 = param2;

$response = $call->index($input)

}

Controller2.php

public function Index(Request $request){
dd($request->all());
}

I am getting [] as response.



via Chebli Mohamed

Laravel LdapRecord - get no users from security group

i am using now ldaprecord and it is really a very cool thing :)

so far - i have a litte problem (or a uncorrect understanding) - so maybe you can help me. i`ve defined a "base_dn" to connect to our Microsoft AD.

(in my case "xxx" is our domain).

'base_dn' => env('LDAP_BASE_DN', 'OU=03_Benutzer,DC=intern,DC=xxx,DC=at')

with this base_dn i got all users from "03_Benutzer" and can import them. i think because it is a organizational unit.

in my other case - i want to get all members from a security group. when i try this:

'base_dn' => env('LDAP_BASE_DN', 'OU=MitarbeiterInnen,OU=01_Organigramm,DC=intern,DC=xxx,DC=at')

i got no users to import.

what can i do to import users from a security group in the base_dn?!



via Chebli Mohamed

lundi 15 novembre 2021

Route does not find variable

i need to pass a variable $empresa to my route, but it can't find it.

find the route only as ( / )

Route::get('/', function() {
    if (Auth::guest()) {
        return redirect('/home');
    }
    else {
    
        $empresa = Auth::user()->empresa;
                    return redirect('/' .$empresa);
    }    
});

I only get this problem in web.php file help please



via Chebli Mohamed

vendredi 12 novembre 2021

How can I upload image in local folder laravel?

I am new in larval development, I am unable to upload image in local folder and I am getting error getClientOriginalExtension() on null. Even I have added code enctype="multipart/form-data" in my form, but still am getting the error. Can anyone give suggestion how to resolve this issue. I have given below my code. MyBlade file

        ****MyBlade file****

                   <form action="" method="POST" enctype="multipart/form-data" accept-charset="utf-8"  >
                      @csrf
                     
                      <div class="form-group row">
                          <label for="uname" class="col-md-4 col-form-label text-md-right">User Name</label>
                          <div class="col-md-6">
                              <input type="text" id="username" class="form-control" name="username" required />
                              @if ($errors->has('username'))
                                  <span class="text-danger"></span>
                              @endif
                          </div>
                      </div>
                       <div class="form-group row">
                        <label for="name" class="col-md-4 col-form-label text-md-right">Profile Picture</label>
                        <div class="col-md-6">
                        <input id="image" type="file" class="form-control" name="image">
                    </div>
                 </div>

My Controller File

       if ($files = $request->hasfile('image')) {
        $destinationPath = 'public/image/'; // upload path
        $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
        $files->move($destinationPath, $profileImage);
       }
       else{
         return $request;
       }
        




          

I am getting err:Call to a member function getClientOriginalExtension() on bool



via Chebli Mohamed

How to catch Laravel BroadcastException?

I have a Laravel 5.5 app, in which I generate events, for eg:

event(new ThingChange($thing, 'foo', 'bar'));

Those events implement ShouldBroadcast:

class ThingChange implements ShouldBroadcast  {

I'm broadcasting to Pusher channels. Broadcasting generates a queued job (I'm using the database queue driver), and the Laravel queue worker handles those jobs. The pusher config in config/broadcasting.php is standard:

'pusher' => [
    'driver'    => 'pusher',
    'key'       => env('PUSHER_APP_KEY'),
    'secret'    => env('PUSHER_APP_SECRET'),
    'app_id'    => env('PUSHER_APP_ID'),
    'options'   => [
        'cluster' => env('PUSHER_APP_CLUSTER', 'mt1'),
        'encrypted' => true,
        'useTLS'    => true
    ],
],

This all works. It has been running for years, the config is correct. It also works fine from my local dev machine. There are many questions here on SO about getting the connection to Pusher working at all, often solved by allowing unencrypted connections, or adding curl parameters (example, example, example ...) - this is not one of those questions.

However every now and then, if there are network troubles, broadcasting (unsurprisingly) fails. Last night for example there were network issues at my hosting provider's data centre, and I got a few of these exceptions in my logs:

[2021-11-11 00:22:43] production.ERROR: {"exception":"[object] (Illuminate\Broadcasting\BroadcastException(code: 0): at /path/to/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php:107)

The referenced line 107 throws that exception when Laravel could not connect to Pusher:

throw new BroadcastException(
    is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
);

This is to be expected - network was down, Laravel could not connect to Pusher. There's no way around this, and I'm not trying to magically work around network trouble.

My question is how can I catch that exception? I monitor my production logs and don't want to see these - these events are simply notifications, they are not critical, and while I'd like to log that they failed, I don't want hard ERRORs and multiple full exception traces clogging up my logs.

Trying to catch an exception when generating the event does not work of course, bcs that is not what is actually failing:

try {
    event(new ThingChange($thing, 'foo', 'bar'));
} catch (\Exception $e) {
    // Won't work, firing the event is not what fails ...
}

There is nothing to actually catch in my event class itself, it simply sets some properties for the payload, and defines the channels to broadcast on.

Is there any way to catch this, without modifying Laravel sources?



via Chebli Mohamed

Email verification in laravel when using api routes

I have created laravel api for angular application to register user this is the Registration code and it is working but i want to verify user email after user is registered. I have used laravel default laravel verification in web but i don't have idea of using it in api.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Validator;


class AuthController extends Controller
{
   
    public function __construct() {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

     /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['error_message' => 'Invalid Credentials'], 401);
        }

        return $this->createNewToken($token);
    }

      /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request) {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors(), 422);
        }

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)]
                ));
        return response()->json([
            'message' => 'User successfully registered',
            'user' => $user
        ], 201);
    }

      /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout() {
        auth()->logout();

        return response()->json(['message' => 'User successfully signed out']);
    }

      /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh() {
        return $this->createNewToken(auth()->refresh());
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userProfile() {
        return response()->json(auth()->user());
    }

     /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createNewToken($token){
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60,
            'user' => auth()->user()
        ]);
    }

}

User Model:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;


class User extends Authenticatable implements JWTSubject, MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'email_verified_at'
    ];

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

     /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier() {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims() {
        return [];
    }    

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Please give some solution, Thanks



via Chebli Mohamed

jeudi 11 novembre 2021

Laravel stack trace is not shown on Nginx

I have no idea why in my staging server kept showing Nginx 404 Not Found where there is a crash

enter image description here

while locally, I can see perfectly fine

enter image description here

Even if it show 404 not found, I can go to the log file in Laravel

/storage/logs/laravel-*.log

I can see the crash stack trace... I've tried

APP_DEBUG=true, and APP_DEBUG=false show same result

What did I forget to do?



via Chebli Mohamed

Using Laravel Default Email verification when registering user with API

I have created laravel api for angular application to register user this is the code for registering user and it is working but i want to verify user email after user is registered. How will i use laravel default email verification of web route in api.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Validator;


class AuthController extends Controller
{
   
    public function __construct() {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

     /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['error_message' => 'Invalid Credentials'], 401);
        }

        return $this->createNewToken($token);
    }

      /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request) {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors(), 422);
        }

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)]
                ));
        return response()->json([
            'message' => 'User successfully registered',
            'user' => $user
        ], 201);
    }

      /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout() {
        auth()->logout();

        return response()->json(['message' => 'User successfully signed out']);
    }

      /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh() {
        return $this->createNewToken(auth()->refresh());
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userProfile() {
        return response()->json(auth()->user());
    }

     /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createNewToken($token){
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60,
            'user' => auth()->user()
        ]);
    }

}

User Model:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;


class User extends Authenticatable implements JWTSubject, MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'email_verified_at'
    ];

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

     /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier() {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims() {
        return [];
    }    

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Thanks



via Chebli Mohamed

route getting called two times in angular and laravel

I have created contact us form in angular code, submit function code is as follows:

export class ContactComponent implements OnInit {

  baseUrl = environment.baseUrl;
  mailForm: FormGroup;
  submitted = false;
  constructor(private http: HttpClient, private formBuilder: FormBuilder) { }

  get f() { return this.mailForm.controls; }
  onSubmit() {
  
    this.submitted = true;
    // stop here if form is invalid
    if (this.mailForm.invalid) {
        return;
    }
    //True if all the fields are filled
    if(this.submitted)
    {
      
      // Initialize Params Object
       var myFormData = new FormData();
    
     // Begin assigning parameters
    
        myFormData.append('name', this.mailForm.value.firstname);
        myFormData.append('myEmail', this.mailForm.value.email);
        myFormData.append('mobile', this.mailForm.value.mobile);
        myFormData.append('message', this.mailForm.value.message);
      //post request
      return this.http.post(this.baseUrl+'api/contact-us'
      , myFormData).subscribe((res: Response) => {
        
  
    });  
    }
   
  }

HTML Component:

<form [formGroup]="mailForm" (ngSubmit)="onSubmit()">
<button type="submit" class="btn-login" [disabled]="submitted">Send</button>
</form>

Laravel Routes :

Route::group(['middleware' => ['api','cors']], function ($router) {
    Route::post('/contact-us', [SiteController::class, 'contactUs']);
});

Chrome console:

enter image description here enter image description here

Issue is when i click submit button routes are being called two times

Thanks



via Chebli Mohamed

mercredi 10 novembre 2021

Unique Validation in Laravel 5.4 not working as intended for where() statement

In this table, there are 3 main parameters:

"is_active" (BOOLEAN)
"position" (INT)
"id" 

This is the Unique Rule

'position' => [
'required_if:is_active,true|integer|min:1',
Rule::unique('tablename')->where(function($query) { $query->where('is_active', '=', 'true')->where('id', '!=', $this->id); }),
],

This rule is supposed to make sure that the position parameter to be unique among the data that have is_active set to true. Current issue is that this rule has been ignored, and I'm able to save the update/edit function even though by right is should have failed this validation.

id=1, position=1, is_active=true

id=2, position=2, is_active=true

when I change the position from 2 to 1, as shown above, it should show an error message, instead of being successful. but it isn't the case.

EDIT: $this attribute

ParameterBag {#1862
  #parameters: array:13 [
    "is_active" => "1"
    "order" => "2"
  ]
}

Note: This is in Laravel 5.4 and please do not suggest me to upgrade to Laravel 8, etc.



via Chebli Mohamed

Not null violation: 7 ERROR: null value in column - Laravel 5.8

I don't understand this, I alter my table to add these columns

Schema::table('clusters', function($table)
{

    $table->string('ssaEnabled',1)->default('0');
    $table->string('ssaBackendUrl')->default(NULL);
    $table->string('ssaPortalApiUrl')->default(NULL);

});

in my store() I have this

$cluster->ssaEnabled            = Input::get('ssaEnabled','0');
$cluster->ssaBackendUrl         = Input::get('ssaBackendUrl','');
$cluster->ssaPortalApiUrl       = Input::get('ssaPortalApiUrl','');

$cluster->save();

I kept getting

prod.ERROR: SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "ssaBackendUrl" violates not-null constraint

Why ??

  1. I set it to default null already
  2. I also add a backup value in my Input::get() in the 2nd param as an empty string

Any hints?

How can I stop that ?



via Chebli Mohamed

How to Fetch Dynamic Id of an object and show data related to it in Laravel

So let me give you an overview of the problem I am facing. I am working on a project which has handpicked project as shown below on home page.click to see image

So now I want to show all the associated properties with the specific projects like this click to see image

I have a databse table named "properties" which has a column "project_id". I want this "project_id" to be dynamic . Right Now I am entering the project id manually i.e. 1,2,3,4.

This is the ajax I am using in my blade file

<script>
     $(document).ready(function(){
        getProperties();
        function getProperties() {
            $.ajax({
        url:'/handpickedproperties/{$id}',
        type:'POST',
        data:{'property_type':property_type},
        success:function(response){
            if(response.success){
                var str = '';
                stringlength = 135;
                if($( window ).width()<1363)
                    var stringlength = 100;
                $.each(response.data, function(k,v){
                    description = v.description;
                    if (description.length > stringlength)
                        description = description.substr(0,stringlength)+'.....more';
                    photos = JSON.parse(v.images);
                    if(jQuery.isEmptyObject(photos)){
                        image_count = 0;
                        cover_photo = '/images/default/photo not available.png';
                    }
                    else{
                        image_count = Object.keys(photos['withPhotos']).length;
                        cover_photo = photos.coverPhoto;
                    }
                    area_conversion = JSON.parse(v.area_conversions);
                    str += '<div class="property-box" data-aos="fade-up">\
                                <div class="pic-area">\
                                    <figure><img src="'+cover_photo+'">\
                                        <span class="photo-count">\
                                        <img src="images/photos-icon.png">'+image_count+'</span>\
                                    </figure>\
                                </div>\
                                <div class="listing-property-details">\
                                    <a href="/viewPropertyDetails/'+v.id+'">\
                                        <h5>'+v.name+' in '+v.address+'</a><a href="javascript: void(0)" onclick="addFavourite(`'+v.id+'`)" class="wishlist" style="margin-top:0"><img src="/images/home/heart2.png" id="pic_'+v.id+'"></a><a href="/viewPropertyDetails/'+v.id+'"></h5>\
                                        <span class="price-box">\
                                            <strong>'+v.currency+v.price+v.price_unit+'</strong>\
                                            '+v.currency+' '+v.price_per_area+'/sq.ftadsds.\
                                        </span>\
                                        <span class="area-box">\
                                            <img src="/images/listing-area.png">\
                                            <strong><span class="sq_ft" style="width:75%;display:inline-block;">'+v.area_per_sq_ft+' sq.ft.</span>\
                                            <span class="sq_mt" style="width:75%;display:none;">'+area_conversion.sq_mt+' sq.mt.</span>\
                                            <span class="sq_yrd" style="width:75%;display:none;">'+area_conversion.sq_yrd+' sq.yrd.</span></strong>\
                                            ('+v.carpet_area+') Carpet Area\
                                        </span>\
                                        <span class="bed-box">\
                                            <img src="/images/listing-bed.png">\
                                            <strong>'+v.bedroom+' BHK</strong>\
                                        </span>\
                                        <span class="bath-box">\
                                            <img src="/images/listing-bath.png">\
                                            <strong>'+v.bathroom+' Bath</strong>\
                                        </span>\
                                        <div class="clear"></div>\
                                        <p class="property-brief" style="color:black;">'+description+'</p></a>';
                    if(v.featured == 1)
                        str += '<label style="margin-right: 5px;" class="featured-highlight-buttton">Featured</label>';
                    if(v.verified == 1)
                        str += '<label style="margin-right: 5px;" class="highlight-buttton">Verified</label>';
                    if(v.construction_status == 3)                      
                        str += '<label style="margin-right: 5px;" class="highlight-buttton">Under Construction</label>';
                    if(v.construction_status == 4)
                        str += '<label style="margin-right: 5px;" class="highlight-buttton">Ready to Move</label>';
                                // <label class="highlight-buttton">Resale</label>
                    str += '</div>\
                                <div class="listing-box-bottom">\
                                    <span>\
                                        Posted on '+v.creation_date+' by '+v.created_by+'\
                                        <a href="/total-listed-properties" target="_blank"><strong>'+v.posted_by+'</strong></a>\
                                    </span>\
                                    <a href="#" onClick = "contactDetails(`'+v.id+'`);">Contact '+v.posted_by+'</a>\
                                </div>\
                            </div>';
                });
                $('#results_number').empty();
                $('#results_number').append(Object.keys(response.data).length);
                $('#property-data').append(str);
                $('#no-result-found-div').hide();
            }
            else{
                $('#property-data').empty();
                $('#results_number').empty();
                $('#results_number').append(0);
                $('#no-result-found-div').show();
            }
        }
    });
        }
     });   
</script>

enter code here

This is my controller Code

 public function handpickedProperties(Request $request,$id)
  
    {
        try
        {
            $data           = $request->all();
            $validator      = Validator::make($data, [
            ]);
            if ($validator->fails())
                return $this->sendError("Validation Failure",$validator->errors(),403);

            $price_min = 0;
            $price_max = 10000000;
            $search = PropertyServices::fetchHandpickedProperties($request->search,$request->type,$request->city,$request->property_type,$price_max,$price_min,$id);
            if(is_array($search))
            return view('site.handpicked-properties');
            else if($search == 0)
                return $this->sendError('Property not found',[],206);
            else if($search == null)
                return $this->sendError('Property not found. Due to Exception in Service',[],500);
        }
        catch(Exception $e)
        {
            Log::error('Exception encountered. PropertyController->searchProperties Exception: '.$e);
            return $this->sendError('Property not found. Due to Exception.',[],500);
        }
    }
enter code here

This is the code I have used in listing

public function fetchHandpickedProperties($search,$type,$city,$property_type,$price_max,$price_min,$id)
    {
        {
            try
            {
               
                $result = Property::where('project_id','2')
                                    ->select('description','images','id','address','name','currency','price','price_unit','price_per_area','area_per_sq_ft','area_conversions','bedroom','bathroom','created_by','posted_by',\DB::raw('DATE_FORMAT(created_at,"%M-%d-%Y") as creation_date'),'carpet_area','verified','construction_status','featured','lat','long')
                                    ->get()->toArray();
                    
                return $result;

            }
            catch(Exception $e)
            {
                Log::error('Exception encountered. PropertyServices->searchProperty Exception: '.$e);
                return $result = null;
            }
        }
    }


via Chebli Mohamed

Selecting from multiple tables in laravel

please help.I have a test booking table that looks like this

Schema::create('test_bookings', function (Blueprint $table) {
        $table->unsignedInteger('RequestID');
        $table->string('bookingDate');
        $table->string('timeSlot');
        $table->unsignedInteger('nurse_id');
        $table->timestamps();
    });

and a tests table that looks like this

Schema::create('tests', function (Blueprint $table) {
        $table->unsignedInteger('RequestID');
        $table->unsignedInteger('patientID');
        $table->string('barcode');
        $table->string('temperature');
        $table->string('pressure');
        $table->string('oxygen');
        $table->unsignedInteger('nurseID');
        $table->timestamps();
    });

I want to show the RequestID,bookingDate,timeSlot, name and surname of the nurse only if the test_bookings RequestID is in tests table. This is my nurse table

Schema::create('nurses', function (Blueprint $table) {
        $table->unsignedInteger('nurseID');
        $table->string('name');
        $table->string('surname');
        $table->string('idNumber');
        $table->string('phone');
        $table->string('email');
        $table->unsignedInteger('suburb_id');
        $table->timestamps();


        $table->index('suburb_id');
    });

This is the code that i tried

$tests =  DB::table('tests')
                ->select('RequestID','bookingDate','timeSlot','name','surname')
                ->join('nurses','nurses.nurseID','test_bookings.nurse_id')
                ->join('test_bookings','test_bookings.RequestID','=','tests.RequestID')
                ->get();


via Chebli Mohamed

mardi 9 novembre 2021

Conditionally validate request fields in Laravel 5

My variable carType gets a string value.

If additionalFields variable is carType should be required when it is a truck or caravan. If carType is a truck, then additionalFields should be a array.

'carType' => 'string',
'additionalFields' => 'required_if:carType,truck,caravan',

How do i add an array validation based on condition?



via Chebli Mohamed

issue in laravel php artisan server [closed]

I have installed a live laravel project on my localhost. when I run there are two warning errors that occur.

Anyone have idea how to fix it

Warning: The use statement with the non-compound name 'DateTime' has no effect in app\helper.php on line 22

Warning: The use statement with the non-compound name 'DateTimeZone' has no effect i
n \app\helper.php on line 23


via Chebli Mohamed

Wildcard-like syntax in an eloquent Where clause to search between two strings

I saw the answer provided in this question Wildcard-like syntax in an eloquent Where clause? now I want to know if is there a way to search between two strings?.

basicasicaly in my code I want to show requests that have a status of new or scheduled.

$requests = DB::table('requests')
        ->select('requestDate','requestTime','status','requestID')
        ->where('requestorID', '=',$userID)
        ->where('status', 'LIKE','%New%')
        ->get();


via Chebli Mohamed

lundi 8 novembre 2021

create dynamically checkbox in blade

I´m traying to create list of checkbox in my blade with all roles that i have in my DB. I´m doing loop to get all roles and if to check that roles have this user that i´m doing edit:

@foreach($roles as $rol)
   @foreach ($selRoles as $role)
     @if ($role == $rol->id)
        <div class="col-md-4">
          <input type="checkbox" name="rol" checked=checked class="form-check-input" value="" id="">
          
       </div>
     @else
      <div class="col-md-4">
         <input type="checkbox" name="rol" class="form-check-input" value="" id="">
         
      </div>                                                   
     @endif
   @endforeach
@endforeach

With this code, my problem it´s that all my roles it´s duplicated. In my controller i have this:

public function edit(User $usuario)
    {
        $roles = Bouncer::role()->orderBy('title', 'DESC')->get();
        $selRoles = $usuario->roles->pluck('id')->toArray(); //selRoles it´s roles from user
    
        $usuario->load('roles');

        return view('admin.empleados.edit', compact('usuario', 'roles','selRoles'));
    }

and retult in blade it´s:

teleoperadora
teleoperadora
teleoperadora
repartidor
repartidor
repartidor
prueba
prueba
prueba
Jefe de equipo
Jefe de equipo
Jefe de equipo
jefa-sala
jefa-sala
jefa-sala
instalador
instalador

for example. I don´t know that i´m doing bad for get this result in my blade. Anybody can help me please?

Thanks for read and help. Sorry for my english



via Chebli Mohamed

Laraval storage:link command failing because of Database Error

When I am executing the below command in Laraval

php artisan storage:link

It throws a database connection error

 Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `settings`)
 at /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669

I don't see any relation between storage:link command and database connection. Just want to understand what exactly can be wrong here.



via Chebli Mohamed

How can I fix this error related to to controller?

I have a problem, thank you for your help. I want this to be done in the Store method when a person submits a question But it gives me an error that says: thread_id required ???!

  Subscribe::query()->create([
        'thread_id'=>$thread->id,
        'user_id' => auth()->user()->id
    ]);

This is the code for my Store method, which includes the subscribe model:

 public function store(Request $request,Thread $thread)
{
    $request->validate([
        'title' => ['required', 'min:3'],
        'description' => ['required'],
        'channel_id' => ['required'],
        'thread_id' => ['required']
    ]);

    Thread::create([
        'title' => $request->title,
        'description' => $request->description,
        'user_id' => auth()->user()->id,
        'channel_id' => $request->channel_id,
    ]);

    Subscribe::query()->create([
        'thread_id' => $thread->id,
        'user_id' => auth()->user()->id
    ]);
    return redirect('/');
}

This is also the code related to View

<form action="" method="post">
@csrf
<input type="hidden" name="thread_id" value="">

<div class=" container-fluid w-75 border border-secondary rounded shadow">
    <div style="font-weight: bolder; font-size: large;" class=" my-3">فرم ارسال پرسش</div>
    <div class="input-group mb-3">
        <div class="input-group-prepend">

        </div>
        <input type="text" name="title" class="form-control" placeholder="موضوع" aria-label="Username" value=""
               aria-describedby="basic-addon1">
    </div>
    
    <div class="input-group">
        <textarea name="description" class="form-control" aria-label="With textarea" placeholder="متن پرسش"
                  style="height: 200px;"></textarea>
    </div>


    <div class="input-group mt-3 " style="direction: ltr;">
        <select name="channel_id" class="custom-select" id="channel_id" >
            <option selected disabled value="">انتخاب عنوان</option>
            @foreach(\App\Models\Channel::all() as $channel)
                <option value=""></option>
            @endforeach
        </select>

    </div>

    <div class="my-3" style="width: 100px;">
        <button class="btn btn-success" type="submit">ارسال</button>
    </div>


</div>

the problem about this code on view

<input type="hidden" name="thread_id" value="">

also i sent the Thread model on view

 public function create(Thread $thread)
{
    return view('answer-question.thread.thread-create',compact('thread'));
}

this is subcribe database enter image description here



via Chebli Mohamed

dimanche 7 novembre 2021

Cors issue in Laravel and angular application

I have hosted laravel and angular application on two different sub domain

but now getting this error :

Access to XMLHttpRequest at 'https://ift.tt/3wvKosX' from origin 'https://ift.tt/3BSZXfr' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

CORS Middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
$response->header('Access-Control-Allow-Origin', '*')->header('Access-Control-Allow-Headers', 'Content-type, X-Auth-Token, Authorization, Origin');

return $response;
    }
}

api.php

Route::group(['middleware' => ['api','cors'],'prefix' => 'auth'], function ($router) {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::post('/refresh', [AuthController::class, 'refresh']);
    Route::get('/user-profile', [AuthController::class, 'userProfile']);    
});

Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        //'guest' => \App\Http\Middleware\CORS::class,
        'cors' => \App\Http\Middleware\CORS::class,
    ];
}

config/cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

Any suggestion to resolve this issue. Thanks



via Chebli Mohamed

Access to XMLHttpRequest at 'https://......login' from origin 'https://.....r.in' has been blocked by CORS policy

I have hosted laravel and angular application on server it was working before but now it is throwing below error :

Access to XMLHttpRequest at 'https://......login' from origin 'https://.....r.in' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have created CORS middleware :

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        header('Acess-Control-Allow-Origin: *');
        header('Acess-Control-Allow-Origin: Content-type, X-Auth-Token, Authorization, Origin');
        return $next($request);
    }
}

api route file:

Route::group(['middleware' => 'api','cors','prefix' => 'auth'], function ($router) {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/user-profile', [AuthController::class, 'userProfile']);    
});

Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'guest' => \App\Http\Middleware\CORS::class,
    ];
}

Any solution is highly appreciated, Thanks



via Chebli Mohamed