lundi 4 septembre 2023

Xlsx file not able to read data in laravel 5.2

I am using laravel 5.2 and "maatwebsite/excel": "~2.1.0", I am not able to read xlsx file data i am getting response empty data My code is here

Excel::load($filePathNew, function($reader) {
$results = $reader-\>get();
$results = $reader-\>all();
dd($results);
});


via Chebli Mohamed

dimanche 3 septembre 2023

Laravel SearchDropdown - to implement SearchDropdown in my laravel project

i want to implement SearchDropdown in my laravel project so i have in issue that i do not have search results this is my SearchDropdown.php file `<?php namespace App\Livewire;

use Livewire\Component; use Illuminate\Support\Facades\Http;

class SearchDropdown extends Component { public $search = '';

public function render()
{
     $searchResults = [];

    if (strlen($this->search) >= 2 )
    // if (!empty($this->search))
    {
        $response = Http::withToken(config('services.tmdb.token'))
            ->get('https://api.themoviedb.org/3/search/movie', [
                'query' => $this->search,
            ]);

        if ($response->ok()) {
            $searchResults = $response->json()['results'];
        }
    }

    return view('livewire.search-dropdown', [
        'searchResults' => collect($searchResults)->take(7),
    ]);
}

}`

and this is my component `

<div wire:loading class="spinner top-0 right-0 mr-4 mt-3"></div>

@if (strlen($search) >= 2)
    <div class="absolute bg-gray-800 text-sm rounded w-64 mt-4">
        @if ($searchResults->count() > 0)
            <ul>
                @foreach ($searchResults as $result)
                    <li class="border-b border-gray-700">
                        <a href="" class="block hover:bg-gray-700 px-3 py-3 items-center transition ease-in-out duration-150">
                            @if ($result['poster_path'])
                            <img src="https://image.tmdb.org/t/p/w92/" alt="poster" class="w-8">
                        @else
                            <img src="https://via.placeholder.com/50x75" alt="poster" class="w-8">
                        @endif
                        <span class="ml-4"></span>
                    </a>
                    </li>
                @endforeach

            </ul>
        @else
            <div class="px-3 py-3">No results for ""</div>
        @endif
    </div>
@endif
`

i try to implement SearchDropdown in my laravel project to wite a movie name in the SearchDropdown but i have no resualts



via Chebli Mohamed

vendredi 1 septembre 2023

Seeking Guidance for Migrating Laravel 5.4 Web App to a New Domain [closed]

I'm in need of your valuable advice.

We are currently working on a Laravel project, and our Laravel web app is connected to a mobile app via an API. Now, we're planning to move the web app to a new domain. However, there's a catch - our Laravel version is a very outdated 5.4 version, and unfortunately, we've lost access to the source code. Luckily, we do have a server backup file.

Could anyone kindly suggest a method for deploying this code on the new domain?

Thank you in advance.

Laravel 5.4 Web App Migration Help Required.



via Chebli Mohamed

Authentification failed [closed]

I develop in Laravel and I need to do authentication with two roles but it does not work : if the role of the user is a technician or engineer the system must go to the homet.blade.php page ,

here the code is what the syntax is just :

@if (Auth::user()->role == "Technician" xor Auth::user()->role == "Engineer" )

window.location = "/homet";

@endif

I tried to insert the logical operation "xor" but it does not work



via Chebli Mohamed

mardi 29 août 2023

How to fetch data from database using multiple dropdown in form laravel 5.4?

I have blade view which is basically a form consists of 3 dropdown value such as Division,District and Upazila. Blade View

my Index blade looks like below image. Index Blade

after the submit button clicked,it shows me page not found.i don't have any idea why it didn't go to controller method. enter image description here

Route:

Route::get('booksnew/allinstbyupazila', [
                'as' => 'admin.booksnew.allinstbyupazila',
                'uses' => 'BooksNewController@allinstbyupazila']);

Controller:

public function allinstbyupazila(BooksRequest $request) {

        $module_name = $this->module_name;
        $module_icon = $this->module_icon;
        $module_model = $this->module_model;

        $module_action = "List";

        $title = "Upazila wise Institute List";
        $page_heading = $title;

        $division = $request->division_id;
        $district = $request->district_id;
        $upazila = $request->upazila_id;
        dd($request->all());

        if ($division == '' || $district == '' || $upazila == ''){
            Log::info("'$title' viewed by User:" . Auth::user()->name . '(ID:' . Auth::user()->id . ')');

            return view("backend.$module_name.upazila_input", compact('page_heading', 'title', 'module_name', 'module_icon', 'page_heading', 'module_action'));

        } else {
            if (Auth::user()->hasRole('Administrator')) {
            
                $$module_name = $module_model::where('division_id', $division)
                    ->where('district_id', $district)
                    ->where('upazila_id', $upazila)
                    ->get();
                
            }else

                return redirect()->back()->with('flash_warning', '<i class="fa fa-exclamation-triangle"></i> Do not have the permission');

        }

        Log::info("'$title' viewed by User:" . Auth::user()->name . '(ID:' . Auth::user()->id . ')');
        
        return view("backend.$module_name.index", compact('division', 'district','upazila', 'title', 'module_name', "$module_name", 'module_icon', 'page_heading', 'module_action'));

I try everything i could but didn't find any solution yet.i just need to fetch data from the dropdown value as parameter and show the fetched data in another blade view.help me asap.



via Chebli Mohamed

mercredi 23 août 2023

laravel sanctum api working fine with postman but not working with flutter

I'm New in Laravel but I know flutter here what I am trying to achieve I have created a Laravel Api where token is generated by sanctum and I getting the token properly when I test on postman but when I try this from flutter project I get the token but i get this error

{ "message": "Unauthenticated." }

here is my laravel function in controller

`\public function store(Request $request) { $validator = Validator::make($request->all(), [ 'phone_no' => 'required|digits:10', 'name' => 'sometimes|string|nullable', // Allow empty name 'address' => 'sometimes|string|nullable', // Allow empty address 'longitude' => 'sometimes|string|nullable', // Allow empty longitude and latitude 'latitude' => 'sometimes|string|nullable', // Allow empty longitude and latitude 'accuracy' => 'sometimes|string|nullable', // Allow empty longitude and latitude 'referby_coupon' => 'sometimes|string|nullable', // Allow empty referby_coupon ]); // Check for existing user with the same phone number $user = UserModel::where('phone_no', $request->phone_no)->first();

if ($validator->fails()) {
    return response()->json([
        'status' => 422,
        'errors' => $validator->messages()
    ], 422);
} else {
    if ($user) {
          $user->name = $user->name === 'new' ? '' : $user->name;
            $user->address = $user->address === 'new' ? '' : $user->address;
            $user->longitude = $user->longitude === 'new' ? '' : $user->longitude;
             $user->latitude = $user->latitude === 'new' ? '' : $user->latitude;
              $user->accuracy = $user->accuracy === 'new' ? '' : $user->accuracy;
             $user->referby_coupon = $user->referby_coupon === 'new' ? '' : $user->referby_coupon;
              $token = $user->createToken($request->id)->plainTextToken;

        return response()->json([
            'status' => 422,
            'message' => 'User already exists',
            'token' => $token,
            'data' => $user
        ], 422);
    } else {
        // Generate random coupon
        $coupon = $this->generateRandomCoupon();

    $user = UserModel::create([
            'id' => $request->id,
            'name' => $request->name,
            'phone_no' => $request->phone_no,
            'address' => $request->address,
            'longitude' => $request->longitude,
            'latitude' => $request->latitude,
            'accuracy' => $request->accuracy,
            'own_coupon' => $coupon, // Insert the generated coupon here
            'referby_coupon' => $request->referby_coupon,
        ]);

        if ($user) {
         $token = $user->createToken($request->id)->plainTextToken;

            return response()->json([
                'status' => 200,
                'token' => $token,
                'message' => 'User Created Successfully'
            ], 200);
        } else {
            return response()->json([
                'status' => 500,
                'message' => 'Something went wrong'
            ], 500);
        }
    }
}
}

private function generateRandomCoupon($length = 4) { $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $excludedWords = ['CAT', 'DOG', 'SEX','sex', 'FUCK','fuck']; // Add any words you want to exclude here $coupon = '';
do {
    $coupon = '';
    for ($i = 0; $i < $length; $i++) {
        $coupon .= $characters[rand(0, strlen($characters) - 1)];
    }
} while (UserModel::where('own_coupon', $coupon)->exists() || in_array($coupon, $excludedWords, true));

return $coupon;

}`

this is model class

`

protected $table = 'users';
<?php

namespace App\Models; use Laravel\Sanctum\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;

class UserModel extends Authenticatable { use HasApiTokens, HasFactory, Notifiable;

protected $fillable = [
    'id',
    'name',
    'phone_no',
    'address',
    'longitude',
    'latitude',
    'accuracy',
    'own_coupon',
    'referby_coupon',
    
    
];

protected $primaryKey = "id";

public $timestamps = false;

}`

this is my flutter code

Future<void> setData(String name, String address, String phoneNo,
      String longitudeLatitude, String referByCoupon) async {
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('yyyymmddhhmmsskkmm').format(now);
    var formData = FormData.fromMap({
      'id': formattedDate,
      'name': 'new',
      'address': 'new',
      'phone_no': MyLogin.phoneNoTransfer,
      'longitude': 'new',
      'latitude': 'new',
      'accuracy': 'new',
      'own_coupon': "new",
      'referby_coupon': referByCoupon.isNotEmpty ? referByCoupon : 'new'
    });
    try {
      Dio dio = Dio(BaseOptions(validateStatus: (statusCode) {
        if (statusCode == 422) {
          return true;
        }
        if (statusCode == 200) {
          return true;
        }
        return false;
      }));
      final response = await dio.post(
        options: Options(headers: {
          HttpHeaders.contentTypeHeader: "application/json",
        }),
        '$startUrl/public/api/user',
        data: formData,
      );
      print(response);
      print(response.statusCode);

      String token = response.data['token'];

      if (response.statusCode == 200) {
        SharedPreferencesPersonalData().setToken(token);
        SharedPreferencesPersonalData().setID(int.parse(formattedDate));
        SharedPreferencesPersonalData().setPhoneNo(phoneNo);
      } else if (response.statusCode == 422) {
        final result = response.data['data'];

        print(result);

        int apiId = int.parse(result['id'].toString());
        String apiPhoneNo = result['phone_no'].toString();
        String apiName = result['name'].toString();
        String apiAddress = result['address'].toString();
        String ownCoupon = result['own_coupon'];
        String referByCoupon = result['referby_coupon'];

        SharedPreferencesPersonalData().setID(apiId);
        SharedPreferencesPersonalData().setPhoneNo(apiPhoneNo);
        SharedPreferencesPersonalData().setName(apiName);
        SharedPreferencesPersonalData().setAddress(apiAddress);
        SharedPreferencesPersonalData().setOwnCoupon(ownCoupon);
        SharedPreferencesPersonalData().setReferByCoupon(referByCoupon);
        SharedPreferencesPersonalData().setToken(token);
      } else {
        print(response.statusCode);
      }
    } catch (e) {
      print(e);
    }
  }

I am excepting the token work properly but its not working and i notices that when I use postman in access token id all column fill but when I use login in flutter tokenable id is 0 and i hosted in hostinger

enter image description here

futter where i am getting error enter image description here



via Chebli Mohamed

dimanche 20 août 2023

Undefined variable $artikels in foreach laravel

I have a problem with my laravel project where i can't show my data in the table. It keeps giving me undefined veriable $artikels in my writer.blade.php

So this is my controller

namespace App\Http\Controllers;

use App\Models\Artikel;
use Illuminate\Http\Request;

class ArtikelController extends Controller
{
    public function index()
    {
        $artikels = Artikel::all(); // Replace 'Artikel' with your actual model name

        return view('writer', compact('artikels'));
    }
}

this is my view in writer.blade.php

<table class="table table-bordered">
        <tr>
            <th>Image</th>
            <th>Judul</th>
            <th>Kategori</th>
            <th>Tag</th>
        </tr>
        @foreach ($artikels as $item)
        <tr>
            <td><img src="/gambar_artikel/" width="100px"></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        @endforeach
    </table>

and this is my route

Route::view('/', 'dashboard')->name('dashboard');
Route::view('/AboutMe', 'aboutme')->name('AboutMe');
Route::view('/Writer', 'writer')->name('writer');


Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::resource('/artikel', \App\Http\Controllers\ArtikelController::class);

how do i fix this problem? Thank you :)

I tried finding a lot of tutorials but it didn't fix my problem



via Chebli Mohamed