mercredi 24 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

mardi 23 juin 2020

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

New upload changes upload of storage upload dirs?

I am working on a project which works fine on localhost but once i upload it to my server it calls the standard upload directory /storage/public/upload while the images are located in /storage/app/public/upload. I just added some changes to the markup and reuploaded the project with some more updated composer dependencies - and now the images show the default path. I have tried to delete history etc. I am new to laravel but good at php. Do you also have to restart bt running php artisan serve? Wouldn't apache work by default with it here?

I found a similar question here but the solution is already implemented in my code. How to change storage path in laravel 5.3 to public?



via Chebli Mohamed

Cannot get data from dynamic input fields using foreach loop in Laravel

I have multiple multiple input fields in my form that are being created dynamically, Now there are two sets one is attribute and the other is attribute values like this:

<input type="text" name="attribute_name[attr_1]" placeholder="Attribute Name" class="form-control" required="">

<input type="text" name="attribute_value[][attr_1]" placeholder="Attribute Value" class="form-control" required="">

<input type="text" name="attribute_value[][attr_1]" placeholder="Attribute Value" class="form-control" required="">

<input type="text" name="attribute_name[attr_2]" placeholder="Attribute Name" class="form-control" required="">

<input type="text" name="attribute_value[][attr_2]" placeholder="Attribute Value" class="form-control" required="">

<input type="text" name="attribute_value[][attr_2]" placeholder="Attribute Value" class="form-control" required="">

Now using foreach loop, first i want to get all the attribute fields, then in the inner loop i want to am getting the attribute values like in the code below:

foreach($request->input('attribute_name') as $attrKey => $val)
{
    foreach ($request->input('attribute_value.*.'.$attrKey)  as $attr_valKey => $value) {
        $attribute_value=$value;
    }
}

$request->input('attribute_name') contains Array ( [attr_1] => Color [attr_2] => Size )

The concept i'm using is i don't know the key because it is dynamic, so i'm first trying to loop through all the attribute name one by one and then in the inner loop extract attribute values.

For first time i'm getting the attribute and its related value for second attribute, i didn't get any value.



via Chebli Mohamed

Laravel run batch of commands between hours

There are some commands:

protected function schedule(Schedule $schedule)
{
    $schedule->command('Events:complete')->everyFiveMinutes();
    $schedule->command('Payments:authorize')->everyFiveMinutes();
    $schedule->command('Requests:processing')->hourly();
}

Every one of them should be performed with their own periodicity. But I wanna add one more condition - run that commands only between 08:00 and 20:00. Can Laravel do it, or should I check time via pure php? Laravel 5.4



via Chebli Mohamed