mercredi 24 juin 2020

Laravel Api and Web Authentication At Same Time

i'm building cross-platform app so i have website and mobile app. also I've Authentication part for both website and app.

and i'm using Laravel As backend. For auth i found something called "Auth Guards" and there are two default Auth guard in Laravel, one for web and other for API.

But i'm a bit confused cause i found that you can't use both Auth Guards at the same time.

So, is there any way to build authentication system based in one Database Table For Website an Mobile.

NOTE i need any solution except Firebase Auth



via Chebli Mohamed

Azure AD identity provider with laravel 5.2

Can I implement azure AD as a identity provider with my laravel version 5.2? If yes can anyone give me link or suggest something about it? you can also suggest me another identity provider which will be compatible with laravel 5.2.



via Chebli Mohamed

Search value in array in Laravel Blade

I am beginner in Laravel.

I have array in variable $selectedProductFeatures:

array:9 [▼
  0 => array:9 [▼
    "id" => 9
    "product_id" => 3
    "feature_id" => 1
    "key" => "price60"
    "description" => "60"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  1 => array:9 [▼
    "id" => 10
    "product_id" => 3
    "feature_id" => 1
    "key" => "price60_promo"
    "description" => "65"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  2 => array:9 [▼
    "id" => 11
    "product_id" => 3
    "feature_id" => 1
    "key" => "price90"
    "description" => "90"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  3 => array:9 [▼
    "id" => 12
    "product_id" => 3
    "feature_id" => 1
    "key" => "price90_promo"
    "description" => "95"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  4 => array:9 [▼
    "id" => 13
    "product_id" => 3
    "feature_id" => 1
    "key" => "countertop_length"
    "description" => "1000.00"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  5 => array:9 [▼
    "id" => 14
    "product_id" => 3
    "feature_id" => 1
    "key" => "countertop_type"
    "description" => "4"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  6 => array:9 [▼
    "id" => 15
    "product_id" => 3
    "feature_id" => 1
    "key" => "maintenance"
    "description" => "<p>konserwacja</p>"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  7 => array:9 [▼
    "id" => 16
    "product_id" => 3
    "feature_id" => 1
    "key" => "other_title"
    "description" => "tytuł inny"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  8 => array:9 [▼
    "id" => 17
    "product_id" => 3
    "feature_id" => 1
    "key" => "other_description"
    "description" => "<p>opis inny</p>"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
]

return view('admin.products.view', ['selectedProductFeatures' =>$selectedProductFeatures->toArray(), 'productTypes' => $productTypeRepository->allEnables('name', $orderBy = 'asc', $with = []), 'fileCount' => 5, 'fileFolder' => 'products', 'fileId' => $id, 'product' => $this->model->findOrFail($id), 'categories' => $categories, 'taxVat' => $vatRepository->allEnables('value', 'asc'), 'page_title' => 'Produkty', 'page_breadcrumbs' => [['page' => route('product.index'), 'title' => 'Produkty'], ['page' => '#', 'title' => 'Edytuj produkt']]]);

My blade file:

<input type="text" name="price60" value="">
<input type="text" name="price90" value="">

In price60 I need show value from array (array is dynamic).

"key" => "price60" -- this is name input "description" => "60" - this value to show.

In result I need:

For "key" => "price90" and "description" => "90" in input I need show:

<input type="text" name="price90" value="90">

How can I make it?



via Chebli Mohamed

mardi 23 juin 2020

Check a column is empty array or not in Laravel

I have a json column which is set as null by default and casted as array in model. I've used

->where('column_name', '\[\]')->get();

It retrun empty collection.

My question is if i've to check whether a column is empty array or not in where condition what will i do?



via Chebli Mohamed

Using password hash by Laravel for Swift 5

Website store user/pass in Firebase, and pass is hash by Illuminate\Encryption\Encrypter. My IOS app is connect to Firebase, and need to authentication by use/pass what is stored in database (not by Firebase authentication) same as website. I want to know how i can encrypt pass from app to compare with pass in Firebase? I know my case is not common case, and not good program, but i must make it. This is code decrypt by Laravel

Crypt::decryptString($value['acc_password'])) 

I have read link but still not find a answer for me.



via Chebli Mohamed

How to solve MethodNotAllowedHttpException in RouteCollection.php on Laravel 5.0?

I have a form request to update the data in database.

My Controller

public function edit($id)
    {
        //
        $pinjaman = Pinjaman_Tanker::where('no_admin', $id)->firstOrFail();

        return view('pinjaman.edit')->with('pinjaman', $pinjaman);
    }

    public function update(Request $request, $id)
    {
        //

        $pinjaman = Pinjaman_Tanker::where('no_admin', $id)->firstOrFail();
        $validation = Validator::make($request->all(),[
            "tgl_input_pinjam" => "required|date",
            "no_anggota" => "required",
            "jumlah" => "required",
            "kebutuhan" => "string|required",
            "angsuran" => "required",
            "termin" => "required"
        ]);

        if ($validation->fails()){
            return redirect()->back()->withErrors($validation->errors())->withInput();
        }
        $pinjaman -> tgl_input_pinjam = date('Y-m-d', strtotime($request->get('tgl_input_pinjam')));
        $pinjaman -> kebutuhan = $request -> get('kebutuhan');
        $pinjaman -> jumlah = preg_replace('/(?:[.]|\,00)/', '$1', $request->get('jumlah'));
        $pinjaman -> angsuran = preg_replace('/(?:[.]|\,00)/', '$1', $request->get('angsuran'));
        $pinjaman -> termin = $request -> get('termin');
        $pinjaman -> save();

        return redirect(url('pinjaman'));

    }

Route

Route::get('pinjaman/{no_admin}/edit', 'Pinjaman\PinjamanController_Tanker@edit');
Route::put('pinjaman/{no_admin}', 'Pinjaman\PinjamanController_Tanker@update');

The view

<form id="edit_pinjaman" method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="_token" value="">

After I hit submit button, it didn't redirect to 'pinjaman' but show the form back with this error:

MethodNotAllowedHttpException in RouteCollection.php line 207:

in RouteCollection.php line 207

at RouteCollection->methodNotAllowed(array('PUT')) in RouteCollection.php line 194

at RouteCollection->getRouteForMethods(object(Request), array('PUT')) in RouteCollection.php line 142

at RouteCollection->match(object(Request)) in Router.php line 729

at Router->findRoute(object(Request)) in Router.php line 652

at Router->dispatchToRoute(object(Request)) in Router.php line 628

at Router->dispatch(object(Request)) in Kernel.php line 214

and so on

I already followed the guide in laravel 5.0 official documentation and do some research on internet. But this error keeps happening.

How i solve this?

Thank you



via Chebli Mohamed

SQL error when saving Laravel form SQLSTATE[42S22]: Column not found: 1054 Unknown column 'bedrooms' in 'field list' (SQL: insert into `properties`

Good I have a form where I keep a property (house, hotel, etc.) but saving the form gives me the following error

SQLSTATE [42S22]: Column not found: 1054 Unknown column 'bedrooms' in 'field list' (SQL: insert into properties and I don't understand why I have my keys to the other tables and everything related

Controller

public function create()
    {
         $offer = Offer_type::all()->pluck('name','id');
         $detail = Detail::all()->pluck('name','id');
         $characteristics = Characteristic::all()->pluck('name','id');
         $property_type = Property_type::all()->pluck('name','id');
         $departamento = Departament::all()->pluck('name', 'id');
         $spaces = Space::all()->pluck('name','id');

        return view('properties.create', compact('departamento','offer','detail','characteristics','property_type','spaces'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $properti=$request->except('_token');
        
             if($request->hasFile('images')){
                 $properti['images']=$request->file('images')->store('uploads','public');
             }
        Propertie::insert($properti);

        flash("Se ha registrado su propiedad De forma exitosa ")->success();

        return redirect()->route('properties.index');
    }
    

my view with the form

@extends('layouts.app')


@section('content')

<div class="container">
      <div class="card">
         <div class="card-body">
           <form class="form-horizontal" action='' method="POST" enctype="multipart/form-data">
               @foreach ($errors->all() as $error)
                <p class="alert alert-danger"></p><br>
                @endforeach
                @csrf
              <div class="form-group row">
                <label for="nameinput" class="col-sm-2 col-form-label">Name</label>
                <div class="col-sm-5">
                  <input type="text" class="form-control" id="nameinput" placeholder="Name" name="name">
                </div>
              </div>

                  <div class="form-check">
                  <input class="form-check-input" type="radio" value="" name="offer_type_id">
                  <label class="form-check-label" for="rent">
                    Rent
                  </label>
                   </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" value="" name="offer_type_id">
                  <label class="form-check-label" for="sale">
                    Sale
                  </label>
                </div>
             
                 <div class="form-group col-md-6">
                  <label for="inputEmail4">Price</label>
                  <input type="number" class="form-control" id="price" placeholder="price" name="price">
                 </div>
                 
                 
                 
                  <div class="form-row">
                   <div class="form-group col-md-3">
                   
                      <select id="bedrooms" class="form-control" name="bedrooms">
                        <option selected>Habitaciones...</option>
                        <option>1</option>
                      </select>
                    </div>
                    <div class="form-group col-md-3">
              
                      <select id="bathrooms" class="form-control" name="bathrooms">
                        <option selected>Baños...</option>
                        <option>1</option>
                      </select>
                    </div>
                    <div class="form-group col-md-3">
                
                      <select id="parking" class="form-control" name="parking">
                        <option selected>Estacionamientos...</option>
                        <option>2</option>
                      </select>
                    </div>
                        <div class="col-sm-3">
                          <label class="sr-only" for="inlineFormInputName">area</label>
                          <input type="text" class="form-control" id="inlineFormInputName" placeholder="Area" name="area">
                        </div>
                     </div>
                     
                     <div class="form-row">
                         <div class="form-group col-md-3">
                         <select id="year" class="form-control" name="antiquity">
                             <option selected>Antiguedad ...</option>
                            <option value=""></option>
                            
                            @for ($year = -2020; $year <= -1990; $year++)
                            <option value=""></option>
                            @endfor
                        </select>
                        </div>
                        <div class="form-group col-md-3">
                        <select class="form-control" name="furnished">
                            <option value="" selected >Amobado</option>
                            <option value="Si">Si</option>
                            <option value="No">No</option>
                        </select>
                        </div>
                        <div class="form-group col-md-3">
                
                          <select id="floor" class="form-control" name="floor">
                            <option selected>Pisos...</option>
                            <option>1</option>
                          </select>
                        </div>
                        
                    </div> 
                     <div class="form-group">
                        <label for="exampleFormControlTextarea1">Example textarea</label>
                        <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="description"></textarea>
                      </div>
                      <div class="input-group mb-3">
                      <div class="input-group-prepend">
                        <span class="input-group-text">Upload</span>
                      </div>
                      <div class="custom-file">
                        <input type="file" class="custom-file-input" id="inputGroupFile01" name="images">
                        <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
                      </div>
                    </div>
                 
               
                   <div id="map" style="display:block;height:100vh;width:70vw"></div>
    <div class="form-group col-md-6">
        <label for="formGroupExampleInput">Ciudad</label>
        <select name="departaments" id="departaments" class="custom-select mr-sm-2">
            @foreach($departamento as $key => $departament)
            <option hidden selected>Selecciona un Departamento</option>
            <option value="">  </option>
            @endforeach

        </select>
    </div>
    <div class="form-group col-md-6">
        <label for="formGroupExampleInput">Municipio</label>
        <select name="municipalities" id="municipalities" class="custom-select mr-sm-2">
            <option hidden selected>Selecciona un Municipio</option>
        </select>
    </div>
    <div class="form-group col-md-6">
        <label for="formGroupExampleInput2">Direccion</label>
        <input type="text" class="form-control" id="address" placeholder="Direccion" name="address">
        <button type="button" name="search" id="search">Buscar</button>
    </div>
    <div class="form-group col-md-6">
        <input type="hidden" class="form-control" id="lat" placeholder="lat" name="lat">
    </div>
    <div class="form-group col-md-6">
        <input type="hidden" class="form-control" id="long" placeholder="long" name="long">
    </div>
    
     <button type="submit" class="btn btn-primary my-1">Crear</button>
              
            </form>
            </div>
        </div>
    </div>


@endsection

@section('scripts')
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDOoFVMgp-Ydw4EkWQa1HgNYlLDaTzVaFw" async defer></script>
<script>
    var geocoder;
    var map;

    function initMap() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(4.570868, -74.2973328);
        var mapOptions = {
            zoom: 7,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
            },
            navigationControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById('map'), mapOptions);
    }

    function codeAddress(address) {

        geocoder.geocode({
            'address': address
        }, function(results, status) {
            if (status == 'OK') {
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    map.setCenter(results[0].geometry.location);
                    map.setZoom(18);
                    var infowindow = new google.maps.InfoWindow({
                        content: '<b>' + address + '</b>',
                        size: new google.maps.Size(150, 50)
                    });
                    var marker = new google.maps.Marker({
                        position: results[0].geometry.location,
                        map: map,
                        title: address,
                        animation: google.maps.Animation.DROP,
                        icon: "/images/location-propertiess.png",
                    });
                    google.maps.event.addListener(marker, 'click', function() {
                        infowindow.open(map, marker);

                    });
                    $("#lat").val(results[0].geometry.location.lat())
                    $("#long").val(results[0].geometry.location.lng())
                } else {
                    alert('No se encontraron resultados');
                }
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
    $(function() {
        initMap();
        $('#search').on('click', function(e) {
            e.preventDefault();
            if ($('#address').val() == '' || $('#address').val() == NaN) {
                alert('Ingrese una direccion valida');
                return;
            }

            codeAddress($('#address').val() + ', ' + $('#city').val() + ' Colombia');

        })


    })
</script>

@endsection

migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePropertiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('properties', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->nullable;
            $table->string('price')->nullable;
            $table->text('description')->nullable;
            $table->unsignedBigInteger('property_type_id')->nullable();
            $table->unsignedBigInteger('offer_type_id')->nullable();
            $table->unsignedBigInteger('spaces_id')->nullable();
            $table->unsignedBigInteger('departaments_id')->nullable();
            $table->unsignedBigInteger('municipalities_id')->nullable();
            $table->unsignedBigInteger('details_id')->nullable();
            $table->unsignedBigInteger('characteristics_id')->nullable();
            $table->integer('images')->nullable;
            $table->string('url');
            $table->float('lat');
            $table->float('lng');
            $table->string('direction');
            
            $table->timestamps();
            
            $table->foreign('property_type_id')->references('id')->on('property_type');
            $table->foreign('offer_type_id')->references('id')->on('offer_type');
            $table->foreign('spaces_id')->references('id')->on('spaces');
            $table->foreign('departaments_id')->references('id')->on('departaments');
            $table->foreign('municipalities_id')->references('id')->on('municipalities');
            $table->foreign('details_id')->references('id')->on('details');
            $table->foreign('characteristics_id')->references('id')->on('characteristics');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('properties');
    }
}

I have a one-to-many relationship from my model properties to the other models

I don't understand what causes that error if said table is in my migration of spaces

     *
     * @return void
     */
    public function up()
    {
        Schema::create('spaces', function (Blueprint $table) {
            $table->id();
            $table->string('bedrooms');
            $table->string('bathrooms');
            $table->string('parking');
            $table->string('area');
            $table->timestamps();
        });
    }



via Chebli Mohamed