samedi 30 avril 2022

yield inside section in Laravel 8

Iam trying to yield a section inside another section whitch is itself yielded in master.blade.php ,But it does not work .

master.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   
   
   welcome to X store
    
    @yield('content')
    
</body>
</html>

shop.blade.php ( This is the view that i called in the router ) view('shop')

@extends('master')

@section('content') 


<h1> Hello ! This is Shop page </h1>

@yield('products') 


@endsection

products-grid.blade.php => this is the section that i want to yield in Shop view

@extends('shop')


@section('products')

<h3> product 1 </h3>
<h3> product 2 </h3>
<h3> product 3 </h3>
<h3> product 4 </h3>

@endsection

result

welcome to X store
Hello ! This is Shop page


via Chebli Mohamed

jeudi 28 avril 2022

How to get array values using foreach in laravel

I am new to laravel and php. I have this code in one of my controllers

$group_by_precedence = array("true", "false");

and this code in the view

@foreach  ($group_by_precedence as $value)

                    <thead>
                        <tr>
                            <th colspan="8">
                                <a class="collapse-button collapsed" data-toggle="collapse" href="#collapse_&&&&&" aria-expanded="true" aria-controls="collapse_&&&&&" onclick = "loadDealsFor(&&&&&, 'precedence');"  style="width: 100%;display: block;margin: -10px;padding: 10px;">
                                    <i class="zmdi zmdi-plus"></i> <i class="zmdi zmdi-minus"></i> exists
                                </a>
                            </th>
                        </tr>
                    </thead>
                    
                @endforeach 

I tried and not managed to know how to make the code in the view to be duplicated twice, and replace the &&&&& with the values from the $group_by_precedence array, first the true and second the false. currently the bad solution is to duplicate the code in the view, and just change the &&&&& true and false. can someone assist?



via Chebli Mohamed

outlook not receiving mails from laravel hosted website

i have implemented a mailing system in Laravel which send mails to the users when tried from localhost it is sending mails to both gmail and outlook but when i moved the code to production it only gmail accounts are receiving the mails my env file contents are :

MAIL_DRIVER="smtp" 
MAIL_HOST="smtp.gmail.com" 
MAIL_PORT="587"
MAIL_ENCRYPTION="tls" 


via Chebli Mohamed

mercredi 27 avril 2022

laravel 5.8.38 weird route issue with wildcard

I'm running a laravel 5.8.38 on nginx and have this weird route issue

the route is very simple

Route::get('/{appKey?}', 'AppSetupController@index');

that's it nothing more

the {appKey} is something created from time to time by our users with this php function

uniqid("fsapp");

so the appkey will be 18 digits characters like this, and the full url is something like this

mydomain.com/fsapp6268ad9d42fc3

we have thousands of this and everything work well except this one, this one just go straight to 404 i tried to trace the issue on the file AppSetupController on function index, but this exact appKey doesn't even land on this function, it goes straight to 404 and i don't even know how to trace this issue

if i just change even 1 character from this fsapp6268ad9d42fc3 it will go to the correct route and it just work as intended only this one i don't know why always go to 404

============SOLVED================

turns out it was 403 instead of 404, check on chrome's console the real error code was 403, not 404. but on nginx this domain was set showing 404.html on all error code

after further check, turns out there was a folder on public_html/public with that same name as the appkey



via Chebli Mohamed

How can I use laravel localization into vue components?

I'm currently working on application's translation with Laravel Localization (laravel 5.6). I succeed my text translation on blade templates but I have some view using vuejs. Into them I can't use directly laravel localization. I understand that I have to send my translations files (which are in PHP) into the vue in JS.

I found some packages like :

https://github.com/rmariuzzo/Laravel-JS-Localization ; but it doesn't support laravel 5.6 (damned)...

https://github.com/martinlindhe/laravel-vue-i18n-generator ; Laravel 5 package is no longer maintain...

This application use Laravel 5.6 and vue 2. I can't completely reorganize or upgrade Laravel or vue version.

After many research I'm still not able to do it...

Do you know how can I made translation into my vue component?

Thanks a a lot!



via Chebli Mohamed

mardi 26 avril 2022

Upload image to S3 from Tinymce using Laravel 5

I'm trying to upload an image using Tinymce to S3. Original file size is 151kb but on S3 it only goes up 24 bytes. I checked the size of the file that comes from the request to the controller and it is 151kb. Why is it only uploading 24 bytes?

This is my controller

public function upload(Request $request)
    {
        $fileName=$request->file('file')->getClientOriginalName();
        
        $folder = 'tiny/'.$fileName;
        
        $upload = Storage::put($folder, $request->file('file'));
        
        return response()->json(['location'=> url("resources/app/uploads/$fileName")]); 
        
    }

Tiny code

tinymce.init({
        selector: 'textarea',  // change this value according to your HTML
        image_class_list: [
        {title: 'img-responsive', value: 'img-responsive'},
        ],
        height: 500,
        setup: function (editor) {
            editor.on('init change', function () {
                editor.save();
            });
        },
        plugins: ['fullscreen', 'print', 'paste', 'lists advlist','autosave','image','pagebreak','table', 'toc', 'searchreplace', 'export','advcode', 'imagetools', 'autolink'],
        toolbar: 'undo redo | styleselect | forecolor | bold italic | alignleft aligncenter alignright alignjustify | outdent indent | link image | code | export | fullscreen | pagebreak',
        export_ignore_elements: [ 'iframe', 'video', 'audio' ],
        image_title: true,
        automatic_uploads: true,
        images_upload_url: base_url + 'uploadImageText',
        file_picker_types: 'image',
        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function() {
                var file = this.files[0];

                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function () {
                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);
                    cb(blobInfo.blobUri(), { title: file.name });
                };
            };
            input.click();
        },
        content_css: "writer",
        content_style: "body { margin: 0rem auto; max-width: 900px; }" + " p{word-break: break-word !important}" + " .mce-pagebreak { display: block !important; page-break-after: always !important;}",
        pagebreak_split_block: true
    });


via Chebli Mohamed

Same route different controllers

im trying to use same route but different controllers, but not getting a clean and good solution for it, for example my intention is:

Domain.com/category-slug

Domain.com/article-slug

But each one have different controller, using the same structure routes doesnt go to the intended controller, above leave my web.php

Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/{category}', [App\Http\Controllers\QuestionController::class, 'index'])->name('category.list');

Route::get('/{slug}', [App\Http\Controllers\QuestionController::class, 'show'])->name('questions.show');

Does someone got the same situation and how it handle it?



via Chebli Mohamed

lundi 25 avril 2022

Laravel | is it possible to specify 2 different domain in one laravel project

I have one weird requirement from the client to access the website from 2 different domains but it should be the same code base and the same database so is there any way in .env file I can specify both domains?

For example abc.com, xyz.com should point to the same laravel project with the same database & code base.



via Chebli Mohamed

samedi 23 avril 2022

Why does Laravel storage uploads files to the storage directory?

Is there any special reason why Laravel storage uploads files to a directory in the storage folder and then require creating a Symbolic link to make those files accessible publicly?, why not just upload those files into a directory in the public folder instead?. Thanks.



via Chebli Mohamed

What is the purposes symbol @ in PHP $variable at blade laravel 5? [duplicate]

How do you do ?

I would like to ask about symbol @ in PHP $variable in blade laravel 5. This is the code that I get, but unfortunately the previous programmer was is lost.

enter image description here

Please note at this -> .

Why using @ ? and what is different with without @.

Thank you very much



via Chebli Mohamed

vendredi 22 avril 2022

Laravel - how to stop The GET method is not supported for this route from showing

So I have tried looking for an answer to this but I havent had any luck. so context first I have a fully working laravel project with loads of different routes. I'm currently testing it and one of my tests was to check if a user were to use a delete or post route from the URL, I didn't know what the application would do honestly and it outputed the typical : The GET method is not supported for this route. Supported methods: DELETE which I have seen a million times so my question is

Is there a way to stop this error from coming up and instead output an error screen or simply redirect to a different view.



via Chebli Mohamed

mercredi 20 avril 2022

Laravel app with prefixed dot cookie reload login page

I have Laravel app that sometimes refuses login without any error message, just the login view is reloaded.

However, I found a cookie prefixed with . to the domain (HTTPS), when I delete that cookie from the browser's storage, it works fine and login goes well.

enter image description here

I don't know what is the problem and why removing such prefixed cookie with dot solves the issue?

This is .htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
   Redirect 302 /stop /stop.php
    

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f    
    RewriteRule ^ index.php [L]
    

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

Also due to using multiple domains for the same app, config/session.php I set the domain dynamically to be:

 'domain' => env('SESSION_DOMAIN', $_SERVER['HTTP_HOST']?? null),

Is there any hint to help this conditional issue?



via Chebli Mohamed

Laravel increment with custom starting point

I am trying to allot roll numbers to students. there are a lot of students so when I try to do so using eloquent (one by one) server timeout occurs. any idea on how to do so in single update query.

Here is the basic code:

$roll_number = ExamFormSetting::INITIAL_ROLL_NUMBER;

$max_value = StudentExamForm::ofExamYear(request('exam_year_id'))
                                ->max('roll_number');

if ( $max_value > $roll_number ) {

    $roll_number = (integer)$max_value + 1;

}
//after this I query required info and assign roll number one by one which is not optimal solution. 

Here I am getting the current max roll number from the table. each roll number should be unique every year.

If there is no record i.e. max value is empty I want to start from a given number.

Now I want to assign roll numbers using a single update query.

Here is the code to update the roll number.

StudentExamForm::select('student_exam_forms.*')
                   ->ofDegreePart(request('degree_part_id'))
                   ->ofExamType(request('exam_type_id'))
                   ->ofExamYear(request('exam_year_id'))
                   ->join('students', 'students.id', '=', 'student_exam_forms.student_id')
                   ->orderByDesc('theory_exam_center_id')
                   ->orderBy('students.name')
                   ->increment('roll_number', 1);

but the problem is all the selected rows have null in roll number so the increment is not working. Any option to allot roll number to the first row and later increment remaining rows.



via Chebli Mohamed

Laravel: A unit test may not use the database

Here is the code that I am trying to write unit test for:

$towpRepo = \App::make(TransportOrderWithoutPriceRepository::class);
$towp = $towpRepo->findByOrderNumber($orderNumber);
if ($towp) {
   $towp->delete();
}

Here is the findByOrderNumber method:

public function findByOrderNumber($orderNumber)
{
     return TransportOrderWithoutPrice::where('order_number', '=', $orderNumber)->first();
}

Now here is the test code:

$transportOrderWithoutPrice = mockery::mock('Phirater\Domain\TransportOrdersWithoutPrice\TransportOrderWithoutPrice');
$transportOrderWithoutPriceRepo = mockery::mock('Phirater\Domain\TransportOrdersWithoutPrice\TransportOrderWithoutPriceRepository');
$transportOrderWithoutPriceRepo->shouldReceive('findByOrderNumber')->once()->andReturn($transportOrderWithoutPrice);

Now whenever I run the test, it returns the following error:

PhiraterTest\Unit\Phirater\Domain\TransportOrders\CreateTransportOrderFromPriceResponseCommandHandlerTest::testCreateTransportOrder Illuminate\Database\QueryException: SQLSTATE[HY000] [1049] Unknown database 'What are you doing? A unit test may not use the database!' (SQL: select * from transport_orders_without_price where order_number = 1 limit 1)

/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Connection.php:624
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Connection.php:333
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:1719
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:1704
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:481
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:465
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php:77
/home/vagrant/code/phirater-l51/app/Domain/TransportOrdersWithoutPrice/TransportOrderWithoutPriceRepository.php:167
/home/vagrant/code/phirater-l51/app/Domain/Configuration/Events/Listeners/CleanupTrait.php:59
/home/vagrant/code/phirater-l51/app/Domain/Configuration/Events/Listeners/TransportOrderSubscriber.php:84
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:369
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:200
/home/vagrant/code/phirater-l51/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:467
/home/vagrant/code/phirater-l51/app/Domain/TransportOrders/CreateTransportOrderFromPriceResponseCommandHandler.php:117
/home/vagrant/code/phirater-l51/tests/unit/Phirater/TransportOrders/CreateTransportOrderFromPriceResponseCommandHandlerTest.php:90

What am I doing wrong here? I am on laravel 5.5 and phpunit 6.5.14.



via Chebli Mohamed

mardi 19 avril 2022

How to generate QR code for large text data . I need to generate QR for token [duplicate]

I need to generate QR code for token I'm getting from third party API. The size of that token is creating issue. Is there any to generate QR for large text file ?



via Chebli Mohamed

lundi 18 avril 2022

Bad request issue for laravel socialite

I am trying to implement laravel socialite for google. I am using laravel 5.5. Here i am using

"laravel/socialite": "^5.3",

Also generated credentials from https://console.cloud.google.com/apis/dashboard

'google' => [
    'client_id' => '218368033**********',        
    'client_secret' => 'GOCS**********',
    'redirect' => 'http://localhost:8000/oauth/google/callback',
]

In controller I used

public function redirectToProvider()
{
    Socialite::driver('google')->stateless()->user();
}

Now getting error

Client error: `POST https://accounts.google.com/o/oauth2/token` 
resulted in a `400 Bad Request` response: { "error": 
"invalid_request", "error_description": "Missing required 
parameter: code" }


via Chebli Mohamed

dimanche 17 avril 2022

Operation count different id's

i need to do this operation:

introducir la descripción de la imagen aquí

Count the total of each number of records with a different 'rrpp': 1,2,3,4 ∞

I always use this to sum the records of a RRPP:

  $variable = Modelo::where('dia_id' , $request->id)->where('rrpp' , 1)->count('id');

but this way I only get the result of 1 in specific. And what I need is to get the result like this

help, thanks



via Chebli Mohamed

How to downgrade laravel 8 to 5.3?

Please help me, i want to downgrade my laravel from laravel 8 to laravel 5.3, but no guide on the internet, previously I also installed valet too.



via Chebli Mohamed

samedi 16 avril 2022

How to add a unique field in an existing database in laravel, using MongoDB?

     use App\Models\Product;

     $arr = [
         'id'    => 112,
         'name' => 'X1 SP',
         'slug' => 'x1_sp',
         'image' => [
               'imgAvata' => [
                     'url'   => 'abc.com'
                ],
                'imgProd' => [
                      'url'   => 'bcd.com'
                 ],
              ],
          ];
          // I handle :
          $product = Product::find($arr['id']);
          if (isset($arr['image']['imgFb'] && !empty($arr['image']['imgFb']))) {
              $arr['image']['imgFb'][0] = [
                    'url'   => 'aaa.com'
               ]
              $product->update($arr['image']['imgFb'][0]);
           } else {
               $arr['image']['imgFb'][] = [
                    'url'   => 'aaa.com'
                ]
               // way 1:
               $product->update($arr['image']['imgFb']); //Can't add mongoDB because it's empty, can't update
               // way 2:
               $product->create($arr['image']['imgFb']) // duplicate key error collection: product index: slug_1 dup key : { slug: null }
          }

I am checking if the data is already in the database.. If so, I update, if not, I proceed to add that field. But I only want to update a single field, not a lump of data.. When there is data in the database, I have successfully updated it. But when there is no such field in the database, I use the two methods above to fail. Please give me your opinion.

Database that I use : MongoDB + Laravel . Thanks



via Chebli Mohamed

vendredi 15 avril 2022

Laravel conditional response from Model

I have three tables locations, unique_routes and tours, migration example is below.

// locations table
public function up() {
  Schema::create('locations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    // extra data ...
  });
}
    
// unique_routes table
public function up() {
  Schema::create('unique_routes', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('location_id_1')->unsigned();
    $table->integer('location_id_2')->unsigned();
    // extra data ...
  });
  Schema::table('unique_routes', function (Blueprint $table) {
    $table->foreign('location_id_1')->references('id')->on('locations')->onDelete('cascade');
    $table->foreign('location_id_2')->references('id')->on('locations')->onDelete('cascade');
  });
}

// tours table
public function up() {
    Schema::create( 'tours', function ( Blueprint $table ) {
        $table->increments( 'id' );
        // extra data ...
        $table->integer( 'unique_route_id' )->unsigned();
        $table->boolean( 'reverse_route' )->default( 0 );
        // extra data ...
    } );

    Schema::table( 'tours', function ( Blueprint $table ) {
        $table->foreign( 'unique_route_id' )->references( 'id' )->on( 'unique_routes' );
    } );
}

And Models:

class Tour extends Model {
    public function unique_route() {
        return $this->belongsTo( Route::class, 'route_id', 'id' );
    }
}

class UniqueRoute extends Model {
  public function location_one() {
    return $this->belongsTo('App\Location', 'location_id_1', 'id');
  }
  public function location_two() {
    return $this->belongsTo('App\Location', 'location_id_2', 'id');
  }
}

If I need location one name from unique route from tour:


$tour->route->location_one->name

It works OK.

The problem is that sometimes I need location_two object if "reverse_route" on tours is true! The question that I have is, how can I set conditional on Model? Or is there another approach?



via Chebli Mohamed

jeudi 14 avril 2022

Fatal error: require(): Failed opening required '/storage/ssd4/063/18785063/public_html/../peduli_diri/vendor/autoload.php

Error Message After Hosting

Warning: require(/storage/ssd4/063/18785063/public_html/../peduli_diri/vendor/autoload.php): failed to open stream: No such file or directory in /storage/ssd4/063/18785063/public_html/index.php on line 24

Fatal error: require(): Failed opening required '/storage/ssd4/063/18785063/public_html/../peduli_diri/vendor/autoload.php' (include_path='.:/usr/share/pear:/usr/share/php') in /storage/ssd4/063/18785063/public_html/index.php on line 24

Can I Run the Artisan Composer Install & Update Command on my hosting? Please help me I'm new in laravel



via Chebli Mohamed

Laravel 5.8: How to get the matched URL path without queries or parameters in the middle ware?

I'm trying to get current url in laravel without any parameters or query parameters, let's assume I've this route in the api.php file:

test/{id}/get-test-data/{type}

and the url is

test/395/get-test-data/temp

I need to log this basic url in the middle-ware test/{id}/get-test-data/{type} and not the one with parameters,

I've tried this

$route = \Route::current();
$route->uri;

it worked, but when the endpoint being hit the middle-ware print the $route->uri twice as the following

test/395/get-test-data/temp
test/{id}/get-test-data/{type}

is there any way to avoid printing the first line?



via Chebli Mohamed

mercredi 13 avril 2022

how i can How can I redirect to the correct login page in Laravel carrying different middleware?

I made a duplicate of the auth file in the name of admin and modified some related things and everything works fine, but the problem is that when I go to the "/dashboard" link, it is redirected to "login" and I was supposed to be transferred to "dashboard/login" "I think the problem is in the Authenticate.php file, or is it something else? Is there someone who can help me and explain the solution to the problem?

enter image description here

part of admin route code

Route::group(['middleware' => ['guest:admin'], 'prefix'=>'dashboard', 'as'=>'dashboard.'],function(){
Route::get('register', [RegisteredUserController::class, 'create'])->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])->name('password.request');
Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])->name('password.email');
Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])->name('password.reset');
Route::post('reset-password', [NewPasswordController::class, 'store'])->name('password.update');});


via Chebli Mohamed

mardi 12 avril 2022

Method withCount does not exist

I am using laravel 5.4 so i'm trying to count number of relations between two models "Person" and "Permanance" so this is how it is called in my controller $persons = Person::all()->withCount('Permanance')->get(); and this is the error i'm getting

(1/1) BadMethodCallException

Method withCount does not exist. in Macroable.php line 74 at Collection->__call('withCount', array('Permanance'))in PermanancesController.php line 41



via Chebli Mohamed

lundi 11 avril 2022

How to add number_format decimal in laravel in html view?

does anyone know how to add the decimal number_format here?, I don't use the blade from Laravel but I route the view directly to html... so if I add the number_format attribute, I'm confused ;(

<tr dir-paginate="income in incomes | filter:searchText | itemsPerPage:20" total-items="totalItems">
                            <td></td>
                            <td></td>
                            <td>Rp.</td>
                            <td></td>
                            <td></td>
                            <td>
                                <a ng-show="income.incomeImage != ''" target="_blank" href="index.php/incomes/download/"><button type="button" class="btn btn-success btn-circle" title="" tooltip><i class="fa fa-cloud-download"></i></button></a>
                                <button ng-show="$root.can('Incomes.editIncome')" ng-click="edit(income.id)" type="button" class="btn btn-info btn-circle" title="" tooltip><i class="fa fa-pencil"></i></button>
                                <button ng-show="$root.can('Incomes.delIncome')" ng-click="remove(income,$index)" type="button" class="btn btn-danger btn-circle" title="" tooltip><i class="fa fa-trash-o"></i></button>
                            </td>
                        </tr>


via Chebli Mohamed

samedi 9 avril 2022

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'asdf' for key 'user_username_unique' (SQL: update `user` set `username` = asdf

This works on create/store but not on edit/update. I want the user to be updated and the data already exists in the database, the validation error appears. like this in the user store, I added the data, and it worked, even if there was already the same data then a validation error appeared, but in a different update if I update only the address then the old username data is still used and if I change the username it also works but it doesn't if I replace the username with an existing username the validation error does not appear and instead displays the following error. please help me i am still a student!

Error

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'asdf' for key 'user_username_unique' (SQL: update `user` set `username` = asdf, `password` = $2y$10$BYdDToN5jCCuRLdZx70YA.BFgyVIWulL8n/bv5C3VxOVCw6WBN.kO, `kota_id` = 1505, `kecamatan_id` = 1505013, `desa_id` = 1505013004, `user`.`updated_at` = 2022-04-09 14:25:03 where `id` = 4)

User Migration

Schema::create('user', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('nik')->unique()->nullable();
                $table->string('nama')->nullable();
                $table->string('telp')->unique()->nullable();
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('foto')->nullable();
                $table->string('username')->unique();
                $table->string('password');
                $table->enum('level', ['user','admin'])->default('user');
                $table->unsignedBigInteger('provinsi_id')->nullable();
                $table->unsignedBigInteger('kota_id')->nullable();
                $table->unsignedBigInteger('kecamatan_id')->nullable();
                $table->unsignedBigInteger('desa_id')->nullable();
                $table->text('alamat')->nullable();
                $table->rememberToken();
                $table->timestamps();
            });

User Controller Store

  public function store(Request $request)
    {
           $validasi = $request->validate([
               'username' => ['required', 'string', 'min:3', 'max:30', 'unique:user'],
               'email' => ['required', 'email', 'string', 'max:255', 'unique:user'],
               'password' => ['required', 'string', 'min:8'],
               'nama' => ['required', 'string', 'min:3', 'max:50'],
               'nik' => ['required', 'string', 'min:16', 'max:16', 'unique:user'],
               'telp' => ['required', 'string', 'min:12', 'max:13', 'unique:user'],
               'provinsi_id' => ['required'],
               'kota_id' => ['required'],
               'kecamatan_id' => ['required'],
               'desa_id' => ['required'],
               'foto' => ['mimes:jpeg,jpg,png'],
               'level' => ['required'],
               'alamat' => ['required'],
           ]);
           $validasi['password'] = Hash::make('password');
           $create = User::create($validasi);
           if($request->hasFile('foto')){
               $request->file('foto')->move('images/',$request->file('foto')->getClientOriginalName());
               $create->foto = $request->file('foto')->getClientOriginalName();
               $create->save();
            }

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

User Controller Update

public function update(Request $request, $id)
        {
            $user = User::find($id);
            $validasi = $request->validate([
                'username' => ['required', 'string', 'min:3', 'max:30', 'unique:user,id'],
                'email' => ['required', 'email', 'string', 'max:255', 'unique:user,id'],
                'password' => ['required', 'string', 'min:8', 'max:20'],
                'nama' => ['required', 'string', 'min:3', 'max:50'],
                'nik' => ['required', 'string', 'min:16', 'max:16', 'unique:user,id'],
                'telp' => ['required', 'string', 'min:12', 'max:13', 'unique:user,id'],
                'provinsi_id' => ['required'],
                'kota_id' => ['required'],
                'kecamatan_id' => ['required'],
                'desa_id' => ['required'],
                'foto' => ['mimes:jpeg,jpg,png'],
                'level' => ['required'],
                'alamat' => ['required'],
            ]);
            $validasi['password'] = Hash::make('password');
            $user->update($validasi);
            if($request->hasFile('foto')){
                $request->file('foto')->move('images/',$request->file('foto')->getClientOriginalName());
                $user->foto = $request->file('foto')->getClientOriginalName();
                $user->save();
             }
    
            return redirect()->route('user.index');
        }


via Chebli Mohamed

vendredi 8 avril 2022

Laravel Http Client - How to upload file to linkedin Assets API

I wanted to upload a file using Laravel HTTP Client, but I'm not able to understand how to work or attach media to LinkedIn. And moreover, LinkedIn API does not even give back any response after upload this becomes even harder for me to figure out where I went wrong.

But LinkedIn documentation shows an example using the curl command which I successfully achieved to upload a file and even in the postman I was able to do so by choosing the PUT method and body as a binary file.

Below is LinkedIn Doc under the "Upload the Image" section an example is given for bash.

https://docs.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/vector-asset-api?tabs=http#upload-the-image

Below is the small piece of code I'm trying to achieve upload functionality

   Http::attach('file', file_get_contents($request->file('file')), 'perfidious.jpg')
            ->withHeaders([
                'Authorization' => 'Bearer ' . $oauth2_token,
                'Content-Type' => $file->getMimeType(),
            ])->put('https://api.linkedin.com/mediaUpload/C4E22AQFyx5-WPFqU4w/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJDUuJEebKdjgAAAYAIF2PvtGz3bIfDzdyIAomflRbj4jD-Z1lcfP-7NQ&app=201094746&sync=1&v=beta&ut=1S4fxf2p45tWc1')
            ->json();

What I know from Laravel Docs is "file_get_contents" method reads file data as a string.

https://laravel.com/docs/9.x/http-client

Please, anyone, help me guide on how to do it as I have very minimal knowledge in PHP and Laravel. Thanks!



via Chebli Mohamed

jeudi 7 avril 2022

in array how to pass query for perfect result

 $arr = str_replace('"','', $request->course_id);
  $arr = str_replace('"','', $request->stream_id);
    $arr = str_replace('[','', $arr);
    $arr = str_replace(']','', $arr);
    $arr = explode(',',$arr);
      $a = array(College::whereIn('course_id',$arr)->get());
     $b = array(College::whereIn('stream_id',$arr)->get());
    
    $result =  array_merge($arr,$a, $b );
     return $result;

enter image description here

This is code i done, but not get exact result which i want, i want to filter like when pass id course id 1 and value BCA then show BCA college list, college is 1 table and course is another table and common id in both table is course id, what is exact problem in this code



via Chebli Mohamed

mercredi 6 avril 2022

Sail up for Laravel project does not work

I've cloned a repository from GitHub, and when I try to sail up, I get this message: /usr/bin/env: ‘sh\r’: No such file or directory.

The following is from the laravel website which I believe is the solution to my problem:

docker run --rm \
    -u "$(id -u):$(id -g)" \
    -v $(pwd):/var/www/html \
    -w /var/www/html \
    laravelsail/php81-composer:latest \
    composer install --ignore-platform-reqs

The source of the above code: https://laravel.com/docs/8.x/sail#installing-composer-dependencies-for-existing-projects

I've done docker run laravelsail/php81-composer:latest which gives me an error.

Can you please guide me to get my sail up working?

Thanks.



via Chebli Mohamed

cannot run commands in tinkerwell over ssh connection (laravel)

Tinker works just fine when I am ssh'd into my box, but I cannot get it work in tinkerwell.

I'm trying to connect to my local vagrant box with tinkerwell. It is a vagrant box running in windows: ubuntu 20, laravel 5.7, php7.3.33. Tinkerwell 2.25 in Windows 10. I can connect over ssh, but it errors out whenever I run any command:

enter image description here

In Shell.php line 79: Argument 1 passed to _PhpScoperc223a629f245\Psy\Shell::add() must be an ins tance of _PhpScoperc223a629f245\Symfony\Component\Console\Command\Command, instance of Psy\Command\ParseCommand given, called in phar:///tmp/vagrant_t
inker.phar/vendor/symfony/console/Application.php on line 316

I get the same error whenever I try to run any command. On google I found a thread where someone had the same issue, except they were not connecting over ssh, and the thread had no resolution in it (https://github.com/beyondcode/tinkerwell-community/issues/215). I have checked that I only have a single instance of php installed, and its in my $PATH, so the default path of php for the php executable that tinkerwell picks seems correct.



via Chebli Mohamed

mardi 5 avril 2022

laravel - can not change base URL in Docker + Laravel PHP + Nginx

I try to migrate my backend website (containing API service to mobile apps) from LAMP into docker platform. currently this docker split into 3 parts (Laravel App, database & nginx). sofar, the website launch successfully without error.

However, I need base URL to be like below:

http://backend.example.com/public/

so, if i want to login, url will be http://backend.example.com/public/login, also API url with above format like http://backend.example.com/public/api/v1

What I have tried:

  1. Set APP_URL value in .env to http://backend.example.com/public/
  2. Set below setting in config/app.php to:
'url' => env('APP_URL', 'https://backend.example.com/public'),
'asset_url' => env('ASSET_URL', null)
  1. run php artisan route:clear and php artisan migrate

but still not successfull, evertime i launch web browser, url still stuck to:

http://backend.example.com/

http://backend.example.com/login/

http://backend.example.com/api/v1/

etc

any idea to overcome above problem?

===Additional Note

  1. nginx conf for nginx docker:
server {
    listen 80;
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/public;
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        gzip_static on;
    }
}
  1. original base URL in LAMP are http://backend.example.com/public/, in original i'm using LAMP (Apache+PHP+MySQL) but in current Docker I'm using (Nginx + MySQL + php:7.4-fpm), however because an error, i change something so original base url cannot be achieved anymore...

  2. Reference of This Migration can be found here.



via Chebli Mohamed

How to pass many records through Form in Laravel 8?

The essence of the problem is that I started to learn Laravel and I can not find information on how to pass many fields through the form, followed by validation. Form example:

How to do it right?

`<form class="mt-5" method="post" enctype="multipart/form-data"
    @isset($word)
        action=""
    @else
        action=""
    @endisset
@csrf
@isset($word)
    @method('PUT')
@endisset
<table class="table table-responsive-md">
    <tbody>
        <tr>
            <th>ID</th>
            <th>English</th>
            <th>Transcription</th>
            <th>Russian</th>
            <th>Ukrainian</th>
            <th>Module</th>
            <th>Action</th>
         </tr>
         @for($i = 1; $i < 3; $i++)
            <tr>
                <td></td>
                <td><input type="text" name="eng[]" class="form-control"
                                           value=""></td>
                <td><input type="text" name="transaction[]" class="form-control"
                                           value=""></td>
                <td><input type="text" name="ru[]" class="form-control"
                                           value=""></td>
                <td><input type="text" name="uk[]" class="form-control"
                                           value=""></td>
                <td><input type="text" name="category_id[]" class="form-control"
                                           value=""></td>
                <td></td>
             </tr>
           @endfor
       </tbody>
    </table>
    <a class="btn btn-secondary mt-4" href="">Back</a>
    <button class="btn btn-success  mt-4">Save</button>
</form>`

The output is like this, but I know for sure that this is not right.

^ array:6 [▼ "_token" => "Olp8kMQIFoDP9OOvV5YRihcV3FpKIHofxfYk8W7M" "eng" => array:2 [▶] "transaction" => array:2 [▶] "ru" => array:2 [▼ 1 => "www" 2 => "qqq" ] "uk" => array:2 [▶] "category_id" => array:2 [▶] ]



via Chebli Mohamed

lundi 4 avril 2022

i can´t save my image or my file when upload it

My problem it´s, mi folder it´s created but my file it´s not uploaded. i have this code:

if(isset($request->file_job)){
            $pathFolder = storage_path('app/contratos/'.$tarea->contratoTrey->serie->SERIE.'-'.$tarea->contratoTrey->N_CONTRATO.'/tareas/T-'.$tarea->ntarea);
            $filePath = 'app/contratos/'.$tarea->contratoTrey->serie->SERIE.'-'.$tarea->contratoTrey->N_CONTRATO.'/tareas/T-'.$tarea->ntarea;
           
            if(!\File::exists($pathFolder)) {
                \File::makeDirectory($pathFolder, 0755, true, true);
            }
            
            \Storage::disk('local')->putFileAs($filePath, $request->file_job, ($request->file_job)->getClientOriginalName());
        }

this code generate all my folder structure but not save my file (image) i don´t know that i´m doing wrong.

Thanks for help me



via Chebli Mohamed

Change .htaccess directory in laravel 5.6

Hell folks,

In my project the .htaccess file is placed in the project root directory.

I want it placed in some other directory say '/public/setupfiles' and the project should be able to access it.

Is it possible? if yes thn how?



via Chebli Mohamed

dimanche 3 avril 2022

Laravel 5.6 ajax request internal server error

Hello i'm developing like disliked system based on https://www.itsolutionstuff.com/post/php-laravel-5-like-dislike-system-tutorialexample.html

but the ajax function throwing internal server error

this is my controller

public function ajaxRequest(Request $request)
    {
        $post = Post::find($request->id);
        $response = auth()->user()->toggleLiked($post);

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

and this is my ajax request:

<script type="text/javascript">
    $(document).ready(function() {


        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });


        $('i.glyphicon-thumbs-up, i.glyphicon-thumbs-down').click(function(){
            var id = $(this).parents(".panel").data('id');
            var c = $('#'+this.id+'-bs3').html();
            var cObjId = this.id;
            var cObj = $(this);


            $.ajax({
               type:'POST',
               url:'/ajaxRequest',
               data:{id:id},
               success:function(data){
                  if(jQuery.isEmptyObject(data.success.attached)){
                    $('#'+cObjId+'-bs3').html(parseInt(c)-1);
                    $(cObj).removeClass("like-post");
                  }else{
                    $('#'+cObjId+'-bs3').html(parseInt(c)+1);
                    $(cObj).addClass("like-post");
                  }
               }
            });


        });


        $(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
            event.preventDefault();
            $(this).ekkoLightbox();
        });
    });
</script>

this is the form for clicking the likes

    <span class="pull-right">
       <span class="like-btn">
       <i id="like" class="glyphicon glyphicon-thumbs-up "></i>
     
       <div id="like-bs3"></div>
     <span>
   </span>

what i have done is changing the routes in case it's missing something, but still throwing the same error, what should i do?



via Chebli Mohamed