jeudi 30 avril 2020

Unable to make subquery in laravel 5.1 eloquent

I am trying to get some data using laravel eloquent with subquery, but couldn't make it work. I haven't done this before, so kinda dumb on this. Here is my query:

$assignedTeacherSubjectsObj = AssignedSubjectToTeacher::with(['class_info', 'subject', 'section', 'group', 'user' => function($query) {
                $query->select('user_id', 'full_name', 'phone_no');
            }])
            ->addSelect(["date_wise_assigned_homework" => Homework::whereColumn('tbl_assigned_subjects_to_teachers.institute_branch_version_id', 'tbl_homeworks.institute_branch_version_id')
                ->whereColumn('tbl_assigned_subjects_to_teachers.class_id', 'tbl_homeworks.class_id')
                ->whereColumn('tbl_assigned_subjects_to_teachers.group_id', 'tbl_homeworks.group_id')
                ->whereColumn('tbl_assigned_subjects_to_teachers.section_id', 'tbl_homeworks.section_id')
                ->whereColumn('tbl_assigned_subjects_to_teachers.subject_id', 'tbl_homeworks.subject_id')
                ->whereDate('homework_submissionDate', '>=', $request->HomeworkDateFrom)
                ->whereDate('homework_submissionDate', '<=', $request->HomeworkDateTo)
                ->get();
            ])
            ->where('is_active', 1)
            ->whereIn('institute_branch_version_id', $branchShiftVersionIds)
            ->orderBy('user_id')
            ->orderBy('class_id')
            ->get();

I am getting this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tbl_assigned_subjects_to_teachers.institute_branch_version_id' in 'where clause' (SQL: select * from `tbl_homeworks` where `tbl_assigned_subjects_to_teachers`.`institute_branch_version_id` = tbl_homeworks.institute_branch_version_id and `tbl_assigned_subjects_to_teachers`.`class_id` = tbl_homeworks.class_id and `tbl_assigned_subjects_to_teachers`.`group_id` = tbl_homeworks.group_id and `tbl_assigned_subjects_to_teachers`.`section_id` = tbl_homeworks.section_id and `tbl_assigned_subjects_to_teachers`.`subject_id` = tbl_homeworks.subject_id and date(`homework_submissionDate`) >= 2020-03-24 and date(`homework_submissionDate`) <= 2020-03-30)

Can anyone help me out with this!



via Chebli Mohamed

How to know what columns are presents in a Eloquent query before to execute it in Laravel 5.5?

Im using Laravel 5.5 and I have and QueryBuilder object (from the "Illuminate/Database/Eloquent/Builder" class).

I want to set an orderBy sentence into my query, but only if this field is present and exists in the QueryBuilder object (as column in the select section sentence).

For example, there is an User model, with the following fields ['id', 'firtsname', 'lastname', 'username','description'].

This is my object:

Use App\User;
$query = User::query();
if ($request->input('sort') != null) {
   $model_query->orderBy($request->input('sort'), 'ASC');
}
$users = $query->get();

When I execute it, works fine (if I send you consistent data, of course). But if I set a column what does not exists, it sends and exception. So, the question is, how I can get the columns to retrieve from my $query object? To validate it, and if it's presents, execute the ordening code.



via Chebli Mohamed

Laravel custom pagination exception | Undefined property $pageName

Error message :

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$pageName

I am creating pagination from an array and following is the array.

$array =  [▼
  "A" => 1
  "B" => 2
  "C" => 3
  "D" => 4
  "E" => 5
]

And have the following code :

public function paginate($items, $perPage = 5, $page = null, $options = [])
{
  $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
  $items = $items instanceof Collection ? $items : Collection::make($items);
  return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}

and calling the above method like the following :

$data = $this->paginate($array);
return view('test', ['data' => $data]);

And in test view, I've the following to show pagination links:

<div> </div>

I've no idea what am I missing, I've checked quite a lot.



via Chebli Mohamed

Larave Custom DB Databable

I'm interested in having a Table in my Laravel database, where I can read/write from.

However, I don't want it do be affected by php artisan migrate:fresh or php artisan migrate:refresh commands.

I want to use it as a custom storage for a dataset, which will be imported in the database and updated when needed but only be readable by Laravel.

Thanks in advance.



via Chebli Mohamed

Custom Sequence Number Generation for Order

I have planned a custom sequence number generation for Order Id using MYSQL stored procedures.

Eg, Order id : JWT-000001

Any other suggestion and tips.

And let me know if you have already did this in any other method.



via Chebli Mohamed

My Laravel 5.2 Session doesn't persist when I access a link from Whatsapp(in particular)

Basically the title.

When I share a link from my application on Whatsapp the link redirect to login. Always and only on whatsapp(not on mobile). Discord, facebook etc it does'nt happen. Can someone help with this issue?

UPDATE

This is the link from Whatsapp

<a href="https://mylaravelsite.com.br/somepage/9999" title="https://mylaravelsite.com.br/somepage/9999" target="_blank" rel="noopener noreferrer" class="_3FXB1 selectable-text invisible-space copyable-text">https://mylaravelsite.com.br/somepage/9999</a>


via Chebli Mohamed

Laravel: Having trouble handling multiple files for upload

I have an image uploader that allows multiple images on the frontend (vue.js). When I send it over to Laravel, it's not hitting my foreach loop. I traced the print logs to be executing up until the foreach loops runs but I'm not sure why it's not going through each one unless that's not the correct way.

** JS **

let formData = new FormData();
this.files.forEach((x,index) => {
    formData.append("file", x)
});

axios.post('/admin/upload', formData, {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
})

**Laravel **

print "outside";
if ($request->hasFile('file')) {
    print "inside";
    $files = $request->file('file');
    $stack = [];
    foreach ($files as $file) {
        print "Looping";
        $fileName = Storage::put('/trace/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
        array_push($stack, $fileName);
    }
    return response()->json($stack);
}


via Chebli Mohamed

How to fix Laravel Api passport not validating?

I followed the instructions to set up Laravel passport. A user table and other tables have been created. I copied a tutorial file for a register controller. I am receiving a success message in postman but no required data was entered and it is not doing any validation. Is there anything else I need to do?

<?php

namespace App\Http\Controllers\Api;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
   public function register(Request $request)
   {
        $validatedData = $request->validate([
            'name'=>'required|max:55',
            'email'=>'email|required|unique:users',
            'password'=>'required|confirmed'
        ]);

        $validatedData['password'] = bcrypt($request->password);

        $user = User::create($validatedData);

        $accessToken = $user->createToken('authToken')->accessToken;

        return response(['user'=> $user, 'access_token'=> $accessToken]);

   }
Route::post('/register', 'Api\AuthController@register'); 
Route::post('/login', 'Api\AuthController@login');


via Chebli Mohamed

How to write paths for assets in Laravel+vue project to component with language option?

I have pure laravel structure and my image is under:

project/resources/assets/dist/img/en/image-en.png
project/resources/assets/dist/img/fr/image-fr.png

I want to show images from my vue component in:

project/resources/assets/js/components/Templates/partials/component.vue

What are best option to handle show images in that component? My current solution is:

<template>
<img src="../../../../dist/img//image-.png">
</template>
export default {
name:'example'
  data: {
    lang: 'en'
  }
}

How to remove ../../../../ usage from path? and reuse image path in Vue component.



via Chebli Mohamed

Laravel - Midlleware called after controller construct

I have trouble with checkauth controller that are called after SectionsController constructor - from this is extended ReportController and I don't know why it works like this. I try add middleware at the start of SectionController costruct like $this->middleware('checkauth'); but not working too.

Middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;


class CheckAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check())
        {
            return redirect('/admin/login')->withErrors(['message' => 'You need to login before proceeding']);
        }

        return $next($request);
    }
}

ReportController

<?php

namespace App\Http\Controllers\RMReport\Form;

use App\Http\Controllers\RMReport\SectionsController;
use Illuminate\Http\Request;
use Illuminate\Support\Str;


class ReportController extends SectionsController
{

    public function __construct(){
  /*     dump("REPORT CONTROLLER:");
       dump(\Auth::check());*/
      parent::__construct();
    }
.
.
.
}

SectionsController

<?php

namespace App\Http\Controllers\RMReport;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\Controller;
use Illuminate\Http\UploadedFile;



class SectionsController extends BaseController
{
  use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct(){
      $this->middleware('checkauth');

      dump("SECTIONSCONTROLLER: ");
      dump(\Auth::check());
    }
}

Output from route:list

GET|HEAD | admin/remote-report/{id?} | rm.report | App\Http\Controllers\RMReportFormReportController@form | web,checkauth,checkownerRMreport |  
POST | admin/remote-report/{id?} | rm.report | App\Http\Controllers\RMReport\Form\ReportController@store | web,checkauth,checkownerRMreport |

Output on call GET

"SECTIONSCONTROLLER: "

false

"CHECKAUTH:"

true


via Chebli Mohamed

Setting a custom user verification link issue in laravel

I have been trying to send my users a custom verification email in laravel.

First I run this

php artisan make:notification SendRegisterEmailNotifcation

This has created a file called, SendRegisterEmailNotifcation.php inside my App/Notifications.

Then Inside my user controller's store method, I called that method after user insertion done.

Following is my store function,

public function store(Request $request)
    {
        request()->validate([
            'name' => ['required', 'alpha','min:2', 'max:255'],
            'last_name' => ['required', 'alpha','min:2', 'max:255'],
            'email' => ['required','email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:12', 'confirmed','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
            'mobile'=>['required', 'regex:/^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{8})$/','numeric','min:9'],
            'username'=>['required', 'string', 'min:4', 'max:10', 'unique:users'],   
            'roles'=>['required'],
            'user_roles'=>['required'],
        ]);

        //Customer::create($request->all());

        $input = $request->all();
        $input['password'] = Hash::make($input['password']);

        $user = User::create($input);
        $user->assignRole($request->input('roles'));

        //event(new Registered($user));
        $user->notify(new SendRegisterMailNotification());

        return redirect()->route('customers.index')
                        ->with('success','Customer created successfully. Verification email has been sent to user email.  ');
    }

And this is my SendRegisterMailNotification.php

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class SendRegisterMailNotification extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Click Here to Activate', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Now this process works well, newly created users are receiving their emails.

But the issue is

Normally in laravel activation link has a certain format and once the user hits on the button user's account get activated and store verified date time in the user table, also the link expires in 60 minutes..

Sample verification link,

http://test.site/email/verify/22/3b7c357f630a62cb2bac0e18a47610c245962182?expires=1588247915&signature=7e6869deb1b6b700dcd2a49b2ec66ae32fb0b6dc99aa0405095e9844962bb53c

But in my case I am struggling to set that activation link and the process properly, How can I do that using the above customized email?



via Chebli Mohamed

Laravel CreateApiToken for guest users

In Laravel 5.7, we can pass \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class in the web middleware group. This adds the laravel_token cookie for logged in users.

Is it possible to also pass a cookie for logged out users, so that we can lock API routes with the client middleware, thus authenticating the app but not necessarily the user?



via Chebli Mohamed

How to add multiple rows for same record in laravel?

image

As you can see the image has Add row button . which add multiple rows for one record . I am trying to design database for this but confuse about this step. One thought is I should store this data in the form of json for each column . But I don't think that is a good approach. Please share your ideas How I can add multiple values for same record in database?



via Chebli Mohamed

Foreign key mismatch - "password_resets" referencing "users" on dropColumn

I'm trying to drop a column (lets call it fooboo) on 'users' table with migrations and i'm getting the next error:

General error: 1 foreign key mismatch - "password_resets" referencing "users" (SQL: INSERT INTO users (id, name, email, password, fooboo, created_at, updated_at) SELECT id, name, email, password, fooboo, created_at, updated_at FROM __temp__users)

The up() function in migration class:


    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('fooboo');
        });
    }

This column in particular doesn't have any index, FK or anything that could create conflict. It is just a boolean with a default value FALSE.

I'm getting this error with sqlite when running my unit tests (phpunit). I can't solve this problem just removing the column on migration class that creates it, i need a new migration to run on production server.

Asking our friend google, i can only find this error associated with missed migrations, that's not my case.



via Chebli Mohamed

Laravel email verification link issue

In my laravel application's app url is something like this, admin.site and I'm registering users to my application from the admin panel.

And my client portal url is customer.site.

Once the admin creates an user from admin panel (admin.site) customer receive an account verification email. But the issue is now I need this verification link to be

customer.site/email/...

but the current link is like this

admin.site/email/...

So how can I change this verification link to customer.site

Following is my store function for customer controller

public function store(Request $request)
    {
        request()->validate([
            'name' => ['required', 'alpha','min:2', 'max:255'],
            'last_name' => ['required', 'alpha','min:2', 'max:255'],
            'email' => ['required','email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:12', 'confirmed','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
            'mobile'=>['required', 'regex:/^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{8})$/','numeric','min:9'],
            'username'=>['required', 'string', 'min:4', 'max:10', 'unique:users'],   
            'roles'=>['required'],
            'user_roles'=>['required'],
        ]);

        //Customer::create($request->all());

        $input = $request->all();
        $input['password'] = Hash::make($input['password']);

        $user = User::create($input);
        $user->assignRole($request->input('roles'));

        event(new Registered($user));

        return redirect()->route('customers.index')
                        ->with('success','Customer created successfully. Verification email has been sent to user email.  ');
    }

I'm sending my verification email

event(new Registered($user));

As the customers have no access to the admin site it gives me 403 error message.



via Chebli Mohamed

Customize email verification link issue in laravel

I have admin portal and customer portal in my laravel based application

customer portal: customer.site
admin portal :admin.site

I have option to register for customers on my customer portal. Once an user register a verification email will be sent to user email with the verification link.

sample verification link can be like this: http://customer.site/email/verify/10/2bf6330a5b3693fb6f5380e83e5494f82b87a9f8?expires=1588234415&signature=34ac37e86d1de7e316e717f2e1acf32cd4ee6ed97df56d94496bb2fa79a0f608

so this works perfectly.

Now my issue is,

When I try to create a customer through the ADMIN portal (admin.site) the user creates successfully and the verification mail also sending successfully to the customer address. But, the activation link is something like this

http://admin.site/email/verify/10/2bf6330a5b3693fb6f5380e83e5494f82b87a9f8?expires=1588234415&signature=34ac37e86d1de7e316e717f2e1acf32cd4ee6ed97df56d94496bb2fa79a0f608 

so when a cutomer clicks on that link a forbidden page displays sayin you have no permission to access as customers are not allowed to use the admin portal

How can I set that verification link to customer portal which is customer.site ???

This is my create customer function in the admin controller,

public function store(Request $request)
    {
        request()->validate([
            'name' => ['required', 'alpha','min:2', 'max:255'],
            'last_name' => ['required', 'alpha','min:2', 'max:255'],
            'email' => ['required','email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:12', 'confirmed','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
            'mobile'=>['required', 'regex:/^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{8})$/','numeric','min:9'],
            'username'=>['required', 'string', 'min:4', 'max:10', 'unique:users'],   
            'roles'=>['required'],
            'user_roles'=>['required'],
        ]);

        //Customer::create($request->all());

        $input = $request->all();
        $input['password'] = Hash::make($input['password']);

        $user = User::create($input);
        $user->assignRole($request->input('roles'));

        event(new Registered($user));

        return redirect()->route('customers.index')
                        ->with('success','Customer created successfully. Verification email has been sent to user email.  ');
    }

I'm sending my verification mail from this

event(new Registered($user));

And in my ENV I even added a param called APP_DOMAIN ans set it's value to http://customer.site

also in my app.php I set this

'url' => env('APP_DOMAIN', 'http://customer.site'),

but still the activation mail link redirecting to http://admin.site

How can I fix this issue?



via Chebli Mohamed

mercredi 29 avril 2020

Planning a laravel application - MVC disaster

I am currently creating a small Laravel project. The goal should be. Every User can have 1 or more projects. Every project has data that displayed in Datatables.

The Problem. The data for each projects are different in structure (e.g. Addresses, Questionnaire, ...)

I have now created a separate model / view / controller for each project. But I think it's not the right way. e.g. 100 users have 2 projects, then I need 200 model / views / controller ???

How could I do better? Thanks in advance for your help.



via Chebli Mohamed

Laravel change password issue

For Laravel change password I did like this but why it is not working.. Its not updating password. I have done login page, registration everything working. But this giving me lot of trouble. Below is my code.

        $returnValue = DB::table('users')->where('users_id', $users_id)->where('password', bcrypt($request->opassword))->update(['password'=>bcrypt($request->npassword)]);
    if($returnValue >= 1)
    {
        $success['message'] = "Password updated successfully..";
        return $this->sendResponse($success);
    }
    else
    {
        $error = "Entered Old password is not valid..";
        return $this->sendResponse($error);
    }


via Chebli Mohamed

How to create a route to show Laravel API relationships?

I am able to use Tinker to see relationship between product and reviews. Results are returned.

php artisan tinker
>> App\Model\Product::find(1)->reviews

How do I create a route and a controller to show this relationship because the show method is already being used to show by ID. Do I use the product controller or the reviews controller? Can I show both ways reviews by product and products by reviews?

UPDATED

Here is my products data

Data: [
{
productName: "television",
price: null,
id: 1
},

Here is my reviews data

data: [
{
id: 2,
customerId: "4",
booktitle: null,
description: null,
likes: null,
customer: null,
body: null,
star: null,
productId: "1"
},

Here is my review model

<?php

namespace App;

use App\Product;
use Illuminate\Database\Eloquent\Model;

class Review extends Model
{
    public $timestamps = true;

    protected $table = 'REVIEWS';

    protected $fillable = [
    'booktitle', 'description', 'updated_at', 'created_at',
    ];

/*  public function customer()
    {
        return $this->hasMany(Customers::class); 
    }*/

    public function product()
    {
        return $this->hasMany(Product::class); 
    }

}

I know I don't have a review field in the product table.

This route http://localhost:8000/api/v1/reviews/2/products is trying to run a query select * from [PRODUCTS] where [PRODUCTS].[review_id] = 2 but review_id is not a column name in my table so I don't know where this is being picked up from.

This route http://localhost:8000/api/v1/products/2/reviews is returning a 200 ok but is a blank screen.



via Chebli Mohamed

Laravel without database configuration

I am using laravel but, i do not want any database connectivity. i do not need any database to use for my site. if i delete config/database.php still error. Also if i delete DB config from .env still issue. Is there any way to use laravel without any database configuration.

[1045] Access denied for user 'forge'@'localhost' 

and

database[] not configured

Thanks



via Chebli Mohamed

How add manual pagination in Laravel

I am beginner in Laravel and php. I try show list articles with pagination.

I have controller:

public function poradnik(Request $request)
    {
        MetaTag::set('title', 'name.pl | xxxxx');
        MetaTag::set('description', 'name.pl | xxxxx');
        MetaTag::set('keywords', 'name.pl | xxxxx');

        $data = [
            [
                'title' => 'Strona Internetowa, jak Odnieść Sukces?',
                'desc' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vestibulum luctus ex. Morbi sollicitudin condimentum ante, vel euismod quam rhoncus nec. Ut consectetur convallis libero, ut venenatis libero sagittis ac. Sed hendrerit risus quis luctus dignissim. Morbi tincidunt tempus enim, at volutpat leo placerat sed. Aliquam pharetra dolor faucibus, posuere lacus sit amet, venenatis nulla...',
                'url' => 'poradnik-strona-internetowa-jak-odniesc-sukces'
            ],
            [
                'title' => 'Znaczenie Linków w Budowaniu Pozycji Strony',
                'desc' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vestibulum luctus ex. Morbi sollicitudin condimentum ante, vel euismod quam rhoncus nec. Ut consectetur convallis libero, ut venenatis libero sagittis ac. Sed hendrerit risus quis luctus dignissim. Morbi tincidunt tempus enim, at volutpat leo placerat sed. Aliquam pharetra dolor faucibus, posuere lacus sit amet, venenatis nulla...',
                'url' => 'poradnik-znaczenie-linkow-w-budowaniu-pozycji-strony'
            ],
            [
                'title' => 'Planowanie Sklepu Internetowego',
                'desc' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vestibulum luctus ex. Morbi sollicitudin condimentum ante, vel euismod quam rhoncus nec. Ut consectetur convallis libero, ut venenatis libero sagittis ac. Sed hendrerit risus quis luctus dignissim. Morbi tincidunt tempus enim, at volutpat leo placerat sed. Aliquam pharetra dolor faucibus, posuere lacus sit amet, venenatis nulla...',
                'url' => 'poradnik-planowanie-sklepu-internetowego'
            ]
.........
        ];

        return view('frontend.poradnik.index', ['data' => $data]);
    }

(243 records)

View:

@foreach($data as $value)
                        <li class="guide-item">
                            <a href="">
                                <h2></h2></a>
                            <a href=""><p
                                    class="justify-text">
                                    
                                </p></a>
                        </li>
                    @endforeach

<nav aria-label="Page navigation">
                    <ul class="pagination">
                        <li class="page-item"><a class="page-link" href="#" aria-label="Previous"></a></li>
                        <li class="page-item"><a class="page-link" href="#">1</a></li>
                        <li class="page-item"><a class="page-link" href="#">2</a></li>
                        <li class="page-item"><a class="page-link" href="#">3</a></li>
                        <li class="page-item"><a class="page-link" href="#" aria-label="Next"></a></li>
                    </ul>
                </nav>

How can I add paginate to my code? I need limit 4 records per page. I use Laravel 6 :)



via Chebli Mohamed

hasFile() is giving false for array of file object in controller Laravel

In the front end I having a loop with input type file with name as img_logo[$key] (of the loop) like:

<input type="file" name="img_logo[$key]" class="dropzone" id="" data-index="" >

After submitting the form it goes in the controller, there hasFile() giving true for img_logo but giving false for internal arrays.

I am stuck here only why this is happening, where I am getting it wrong. Although you can see the array's element is also a file object but hasFile() giving them false. Please guide me here I am having an array of files with key, value pair as mentioned below:

array:4 [▼

  "img_logo" => array:2 [▼
    1 => UploadedFile {#462 ▼
      -test: false
      -originalName: "Quotefancy-101003-3840x2160.jpg"
      -mimeType: "image/jpeg"
      -error: 0
      #hashName: null
      path: "/tmp"
      filename: "phpGbtonF"
      basename: "phpGbtonF"
      pathname: "/tmp/phpGbtonF"
      extension: ""
      realPath: "/tmp/phpGbtonF"
      aTime: 2020-04-29 17:59:37
      mTime: 2020-04-29 17:59:37
      cTime: 2020-04-29 17:59:37
      inode: 1078432563
      size: 754605
      perms: 0100600
      owner: 1155
      group: 1157
      type: "file"
      writable: true
      readable: true
      executable: false
      file: true
      dir: false
      link: false
    }
    3 => UploadedFile {#464 ▶}
  ]
]


via Chebli Mohamed

php artisan optimize NULL.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Illuminate\Foundation\Bootstrap

I am setting up an existing Laravel project for the first time in my life,

I am using

  • macOS Catlina version 10.15.2
  • Mongodb 3.2
  • Php 7.2

When I am using composer install I am getting the below error , trying to figure out from last 2 days but no luck php artisan optimize NULL.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Illuminate\Foundation\Bootstrap\ConfigureLogging::configureHandler()

I have gone through multiple links on Stack overflow but no luck , I have deleted vendor folder , and composer.lock multiple times and tried to run composer install but the error is same

Can some body help me to solve this issue

Below is my composer.json

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.3.*",
    "laravelcollective/html": "^5.3.0",
    "laravel/passport": "^1.0",
    "moloquent/moloquent": "dev-master",
    "predis/predis": "^1.1",
    "proengsoft/laravel-jsvalidation": "~1.1",
    "barryvdh/laravel-cors": "^0.9.2",
    "dingo/api": "1.0.x@dev",
    "tymon/jwt-auth": "^1.0@dev",
    "irazasyed/jwt-auth-guard": "^1.0",
    "maatwebsite/excel": "^2.1",
    "davejamesmiller/laravel-breadcrumbs": "^3.0",
    "intervention/image": "^2.3",
    "milon/barcode": "^5.3",
    "h4cc/wkhtmltopdf-amd64": "0.12.x",
    "barryvdh/laravel-snappy": "^0.3.3",
    "brozot/laravel-fcm": "^1.2",
    "yajra/laravel-datatables-oracle": "^6.0",
    "jenssegers/agent": "^2.6",
    "barryvdh/laravel-debugbar": "~2.4",
    "caffeinated/menus": "v3.0.4",
    "laravel-notification-channels/webpush": "^3.0.1",
    "mongodb/mongodb": "^1.5",
    "doctrine/mongodb-odm-bundle": "^3.4"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.0",
    "symfony/css-selector": "3.1.*",
    "laravel/passport": "^1.0",
    "symfony/dom-crawler": "3.1.*",
    "xethron/migrations-generator": "^2.0"
}

}



via Chebli Mohamed

IP of a Outgoing Request from AWS EC2 behind ELB

I have a single EC2 with a EIP behind a ELB. All the incoming requests are hiting the ELB and reaching EC2 webserver, as expected. Now from my PHP application I do a Outgoing Curl request to another server (not in AWS) and check the request IP there, it is showing the ELB IP from Pool. I was expecting it to show the EIP of the EC2.

Is there something that I am missing, do I need any specific header in Curl request to see EIP in another server?

https://forums.aws.amazon.com/thread.jspa?threadID=125346 this thread someone mentioned following, and i was expecting same.

When you receive incoming traffic through the load balancer, the responses will go out the same way. However, traffic that is originating from your instance will not pass through the load balancer. Instead, it is sent directly from the public IP address of your instance out to the Internet. The ELB is not involved in that scenario



via Chebli Mohamed

Laravel Dompdf Show Blank When Display Specific Data

When I use this query:

$admin = \App\Admin::all();

It works.

But when I use this query:

$admin = \App\Admin::where('status', "ACTIVE");

Its shows blank! Even though when I use this query to show data at blade file, it's works!

Why?



via Chebli Mohamed

Diffrent width and height images layout question in Laravel with fancybox

Here is Photo viewer laravel project. it worked well. but I'm having problem about image layout. This below image is my current photo gallery page. As you can see images are not line. looks not good.

enter image description here

Becase each uploaded photo size are diffrent width and height so this happens I guess. I'm using Laravel. And this is fancybox. and I'm using this gentleman's source code. https://www.itsolutionstuff.com/post/laravel-5-image-gallery-crud-example-from-scratchexample.html

I had been changing below css parameter but I couldn't fix. Could you teach me code to fix situation please?

CSS of index.blade.php

  <!-- Latest compiled and minified CSS -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- References: https://github.com/fancyapps/fancyBox -->

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" media="screen">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
   .gallery
    {
        display: inline-block;
        margin-top: 20px;      

    }   

    .form-image-upload{
        background: #e8e8e8 none repeat scroll 0 0;
        padding: 15px;

    }

Image output of Index.blade.php

<div class='list-group gallery'>
            @if($images->count())
                @foreach($images as $image)
                <div class='col-sm-4 col-xs-6 col-md-3 col-lg-3'>
                    <a class="thumbnail fancybox" rel="ligthbox" href="images/">
                        <img class="img-responsive" alt="" src="images/" />
                        <div class='text-center'>
                            <small class='text-muted'>No.</small>
                        </div> <!-- text-center / end -->
                    </a>                

                </div> <!-- col-6 / end -->
                @endforeach
            @endif
        </div> 


via Chebli Mohamed

mardi 28 avril 2020

how to remove "public" from url

hi everyone,

I want to deploy my Laravel project to production. the "public" not removing in base URL.

I have tried this solution:

  1. rename server.php to index.php

  2. cut .htaccess from /public and paste to root

it works but CSS, JS, images not loading.

if anyone knows about this problem please share your knowledge.

Thanks



via Chebli Mohamed

laravel, mysql transaction not working once rollback

I am performing insertion in 4 tables simultaneously using laravel 5.8. When I Submit incomplete Form it will show me error and after that when submit proper data again it will show database error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`matrimonial_db`.`personal_details`, CONSTRAINT `personal_details_ibfk_1` FOREIGN KEY (`site_user_id`) REFERENCES `siteuser` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) (SQL: insert into `personal_details` (`site_user_id`, `updated_at`, `created_at`) values (148, 2020-04-29 05:16:53, 2020-04-29 05:16:53))

First time when i fill form it insert data successfully in all tables but when try again it will show me the error. here is a code

try
        {
            $connection = DB::connection('mysql');
            $connection->beginTransaction();
            $userData = session()->get('registeruser_data');
            $userData->user_type = 'v';
            $userData->save();

            $personal_details= new PersonalDetail;
            $personal_details->site_user_id =$userData->id;
            $personal_details->save();

            $personal_bio= new PersonalBio;
            $personal_bio->site_user_id =$userData->id;
            $personal_bio->save();


            $partner_details= new PartnerDetail;
            $partner_details->site_user_id =$userData->id;
            $partner_details->save();

            $personal_img= new PersonalImage;
            $personal_img->site_user_id =$userData->id;
            $personal_img->save();

            $connection->commit();
            session(['siteuser' => $userData->id]);
            return redirect('/edit/profile');
            // dd($charge);

        }
        catch(Exception $ex)
        {
            $connection->rollBack();
            return redirect::back()->withErrors(['stripe'=>$ex->getMessage()]);
        }


via Chebli Mohamed

how to display 1000 as 1k in laravel 7

I'm new on La-ravel, i want to convert number value

from 1000 to 1k

I have searched documentation of Laravel but i couldn't find. Is there any function for that?



via Chebli Mohamed

Laravel - Input Autocomplete Outside

My options Input autocomplete are out from my input.

Laravel: 5.5

Controller:

$(document).on('focus','.autocomplete_txt_APO',function(){ type = $(this).data('type');

autoType='db_artic';

$(this).autocomplete({ minLength: 0, source: function( request, response ) { $.ajax({ url: "", dataType: "json", data: { term : request.term, type : type, }, success: function(data) { var array = $.map(data, function (item) { return { label: item[autoType], value: item[autoType], data : item } }); response(array) } }); }, select: function( event, ui ) { var data = ui.item.data;
id_arr = $(this).attr('id'); id = id_arr.split("_"); elementId = id[id.length-1]; $('#inp_artic_'+elementId).val(data.db_artic); $('#inp_vrund_'+elementId).val(data.db_vrund); $('#inp_idmat_'+elementId).val(data.db_idmat); } });
});

<table class="table table-bordered">
  <tr>
        <th class="text-center" width="5%">No.</span></th>
        <th class="text-center" width="35%">Material</span></th>
        <th class="text-center" width="12%">Cant</span></th>
        <th class="text-center" width="18%">Vr(UND)</span></th>
        <th class="text-center" width="20%">Vr(TOT)</span></th>
        <th class="text-center" width="10%">Action</span></th>
  </tr>
  <tr>
      ***<td align="center"><span class="badge badge-light" id='sn'>1</span></td>
      <td><input class="form-control autocomplete_txt_APO" autocomplete='off' type='text' 
        data-type="inp_artic" id='inp_artic_1' name='inp_artic[]' 
        placeholder='Ingrese artículo...' required/></td>***

      <td><input class="form-control autocomplete_txt" autocomplete='false' type='number' step='any' 
        data-type="inp_cantd" id='inp_cantd_1' name='inp_cantd[]' 
        placeholder='Cantidad...' required/> </td>

      <td><input class="form-control autocomplete_txt" autocomplete='false' type='number' step='any' 
        data-type="inp_vrund" id='inp_vrund_1' name='inp_vrund[]' 
        placeholder='Valor Unidad...' required/> </td>

      <td><input class="form-control autocomplete_txt" type='number' step='any' 
        data-type="inp_vrtot" id='inp_vrtot_1' name='inp_vrtot[]' 
        placeholder='Valor TOTAL' disabled /> </td>

      <td style="display:none;"><input class="form-control autocomplete_txt" type='number' step='any' 
        data-type="inp_idmat" id='inp_idmat_1' name='inp_idmat[]'/> </td> <!-- colHidden -->

      <td align="center"><button type="button" name="add" id="add" class='btn btn-success addbtn'>+Adicionar</button></td>

    </tr>
    <tfoot>
            <tr>
            <td colspan="5" align="right">&nbsp;</td>
            <td align="center">
              
            <input type="submit" name="save" id="save" class="btn btn-primary" value="Generar" />
            </td>
            </tr>
    </tfoot>
  </table>

image view



via Chebli Mohamed

Saving relationships data in model

This is my store function, Laravel 5.5

Here firstly I am saving address first then account, after that I can attach account id to address id.

But if there is an error saving account data address data will be created but account is not,

Account has one to one relationship with address,

Is there any way to save if there is an error on saving account data address gets deleted or it does not save at all,

Thank you.

public function store(Request $request){

    $address_save = false;
    $account_save = false;


    ///////After Validation//////

    $address = new Address;
    $address->shipping_address1 =  $request->shipping_address1;
    $address->shipping_address2 =  $request->shipping_address2;
    $address->area_id =  $request->area_id;
    $address->city_id =  $request->city_id;
    $address->shipping_state =  $request->shipping_state;
    $address->shipping_pincode =  $request->shipping_pincode;
    $address->shipping_country =  $request->shipping_country;
    $address->billing_address1 =  $request->billing_address1;
    $address->billing_address2 =  $request->billing_address2;
    $address->billing_area =  $request->billing_area;
    $address->billing_state =  $request->billing_state;
    $address->billing_city =  $request->billing_city;
    $address->billing_pincode =  $request->billing_pincode;
    $address->billing_country =  $request->billing_country;
    $address->same_as_shipping =  $shipping;

    $address_save = $address->save();

    $address_id = $address->id;


    $account = new Account;
    $account->title = $request->title;
    $account->fullname = $request->fullname;
    $account->username = $request->username;
    $account->password = $request->password;
    $account->company = $request->company;
    $account->mobile = $request->mobile;
    $account->alt_number = $request->alt_number;
    $account->email = $request->email;
    $account->whatsapp = $request->mobile;
    $account->pan = strtoupper($request->pan);
    $account->gstin = strtoupper($request->gstin);
    $account->registered_at = date("Y-m-d h:i:sa");

    $account->address_id = $address_id;
    $account_save = $account->save();

    $account_id = $account->id;


via Chebli Mohamed

Get the latest row each group based on max date

I am trying to select single from every group where date is max.

I am trying to do with this bellow

|NO | effective   | price     |  level_one| level_two
+---+-------------+----------+|+++++++++++|++++++++++++
|1  | 2011-12-01  |  34       |     1     |    2
|2  | 2011-16-01  |  34       |     1     |    2
|3  | 2011-18-01  | 3434      |     1     |    2
|4  | 2011-16-01  | 3554      |     1     |    3

Result should be

|NO | effective   | price     |  level_one| level_two
+---+-------------+----------+|+++++++++++|++++++++++++
|3  | 2011-18-01  | 3434      |     1     |    2
|4  | 2011-16-01  | 3554      |     1     |    3

But result come

|NO | effective   | price     |  level_one| level_two
+---+-------------+----------+|+++++++++++|++++++++++++
|3  | 2011-12-01  | 34        |     1     |    2
|4  | 2011-16-01  | 3554      |     1     |    3

tried with

$price = App\Price::with('others')
    ->orderBy('effective', 'Desc')
    ->groupBy('level_one','level_two')
    ->get();


via Chebli Mohamed

Laravel count Support Tickets from a user

I have this in the Dashboard Screenshot of the Dashboard

I want that it shows how many Tickets are open / closed / all

How do I do this with this Database?Screenshot from SELECT * FROM tickets

How do I do this that every user see his own open / closed and all tickets?



via Chebli Mohamed

how can i count different multiple same category according to date in laravel

This is my query i want to get sperate count of same category id

DB::table('form_categories')
        ->rightjoin('form_submissions','form_categories.id','=','form_submissions.category_id')
        ->where('form_submissions.user_id' , Auth::user()->id)
        ->where('form_submissions.created_at', '>', Carbon::now()->startOfWeek())
        ->where('form_submissions.created_at', '<', Carbon::now()->endOfWeek())
        ->groupBy('date')
        ->orderBy('date', 'DESC')
        ->get(array(
            DB::raw('Date(form_submissions.created_at) as date'),
            DB::raw('COUNT(form_submissions.category_id) as "category"'), 
        ));


via Chebli Mohamed

error 403 forbidden, when I upload image in laravel 5.8

I testing a code for upload image on laravel 5.8 local and I uploaded image unsuccessful then I recieved error 403 forbidden.

public function store(Request $request)
    {
       request()->validate([
            'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
       ]);
       if ($files = $request->file('profile_image')) {
        // Define upload path
           $destinationPath = public_path('/profile_images/'); // upload path
        // Upload Orginal Image           
           $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
           $files->move($destinationPath, $profileImage);

           $insert['image'] = "$profileImage";
        // Save In Database
            $imagemodel= new Photo();
            $imagemodel->photo_name="$profileImage";
            $imagemodel->save();
        }
        return back()->with('success', 'Image Upload successfully');

    }

error 403 forbidden after I uploaded image and now I can't back to a normal I followed above code on internet and I don't know where I wrong. I need help ! Thank you.



via Chebli Mohamed

Merge existing excel files into one excel file Laravel

The problem is very simple but I can't find a solution anywhere.

I need to combine a few excel files in the storage directory into 1 excel file where every excel file is now a sheet in the new excel file.

I have been experimenting with Maatwebsite/Laravel-Excel (version 3.1) but without success...
Someone an idea how to tackle this problem?



via Chebli Mohamed

lundi 27 avril 2020

record specific data to table with 30minute time interval using laravel

I created two tables,which are rainfall and status_msgs.i want to put record to rainfall table from status_msgs table.now i created a code which can give 10 records of specific UNIT_ID.(UNIT_ID is column of my status_msgs table)UNIT_ ID is A01.now i want that A01 data's record to rainfall table with 30minute time interval.i get data to a variable shown below.and i creadted a model called Statusmsg.

$datas = Statusmsg::where('UNIT_ID', '=', 'A01')->take(10)->get(); foreach ($datas as $data) {

}



via Chebli Mohamed

Laravel SweetAlert not working inside validation fails block

I am using realrashid/sweet-alert version 3.1 with laravel 5.8

the issue is when I am using alert after form success or after validation failed its not working here is my code

public function store(Request $request)
    {
$rules = [
            'title' => 'required',
            'title_desc' => 'required',
            'desc' => 'required',
            'pic' => 'required',
        ];

        $customMessages = [
            'title_desc.required' => 'The Short Description field is required.',
        ];

        $validator = Validator::make($request->all(), $rules, $customMessages);

        if ($validator->fails()) {
            Alert::error('error', 'Validation Errors');
            return back();
        }

        $update_arr = array(
            'title' => "hello",
            'description' => "world",
            'title_desc' => "hello world",
            'added_on' => date("Y-m-d H:i:s")
        );

        StoriesModel::create($update_arr);

        Alert::success('Success', 'Story Created Successfully');
        return redirect('admin/stories');
}

in this code I used alert two times and its not working on both conditions on the other hand

if I am using it like below

public function create()
    {
        Alert::error('error', 'Validation Errors');
        $this->data['title'] = 'Stories';
        $this->data['menu'] = 'stories';
        return View::make('admin.stories.create', $this->data);
    }

Its working fine



via Chebli Mohamed

How to replace/convert double slash to single slash in filesystem laravel 5.8

I want to store excel file to local disk in my server, and do with filesystem in laravel 5.8. This is my filesystem config.

'trading' => [
   'driver' => 'local',
   'root'   => 'C:\Users\Administrator\Documents\SPOP\tradingid',
]

And for do store the excel file, i'm using maatwebsite package like this

public function generate(Request $request){
    $now = date("Y-m-d");
    $id_trans = Transaction::whereIn('id', $request->ids)->pluck('transaction_id');

    $data = Excel::store(new ExportData($id_trans), 'ExcelFile'.$now.'xlsx', 'trading');

    if ($data) {
       return response()->json(['status' => 'success', 'message' => 'Success To Generate']);
    } else {
       return response()->json(['status' => 'error', 'message' => 'Failed To Generate']);
    }
}

When the function executed, i got error message like this enter image description here

I have read any solutions, it's not working, but when the path root using single slash, it's working. So how to convert or replace double slash to single slash in filesystem laravel?



via Chebli Mohamed

How to switch destination mail address by selecting check box in Laravel contact form

This is conctact form and sorking. I would like to switch email destination by User selecting check box.

For example. Here is a coulumn called 'genders'. When User check 'man' select box, Email destination will be [TO]'man_survey@12345677.site' and [CC] is 'man_cc_survey@12345677.site'. When User check 'female' ,Email destination will be [TO] 'female_survey@12345677.site' and [CC] is 'female_cc_survey@12345677.site'

Could you teach me how to add this function to my current code?

my Laravel Framework is 5.7.28

<?php

namespace App\Http\Controllers;

use App\Http\Requests\ContactRequest;
use App\Http\Controllers\Controller;
use App\Contact;

class ContactsController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $types = Contact::$types;
        $genders = Contact::$genders;


        return view('contacts.index', compact('types', 'genders'));
    }

    public function confirm(ContactRequest $request)
    {
        $contact = new Contact($request->all());


        $type = '';
        if (isset($request->type)) {
            $type = implode(', ',$request->type);
        }

        return view('contacts.confirm', compact('contact', 'type'));
    }

    public function complete(ContactRequest $request)
    {
        $input = $request->except('action');

        if ($request->action === 'back') {
            return redirect()->action('ContactsController@index')->withInput($input);        }


        if (isset($request->type)) {
            $request->merge(['type' => implode(', ', $request->type)]);
        }


        // store data
        Contact::create($request->all());

        // send mail
        \Mail::send(new \App\Mail\Contact([
            'to' => $request->email,
            'to_name' => $request->name,
            'from' => 'survey@12345677.site',
            'from_name' => 'from name',
            'subject' => 'Thank you',
            'type' => $request->type,
            'gender' => $request->gender,
            'body' => $request->body
        ]));

        // recive mail
        \Mail::send(new \App\Mail\Contact([
            'to' => 'survey@12345677.site',
            'to_name' => 'to name',
            'from' => $request->email,
            'from_name' => $request->name,
            'subject' => 'you got mail',
            'type' => $request->type,
            'gender' => $request->gender,
            'body' => $request->body
        ], 'from'));


        return view('contacts.complete');
    }
}


via Chebli Mohamed

Create New Passport Client for a User in Laravel and Passport inside Controller

Is there a way to create passport client in Laravel. For example, to create a Token, we can do:

$user = $request->user();
$token = $user->createToken("myApp")->accessToken;

Do we something for Client too?

$user = $request->user();
$token = $user->createClient("myApp")->accessClient;

I checked the documentation and it is possible to create a client using an API, but the example is in Vue.JS

const data = {
    name: 'Client Name',
    redirect: 'http://example.com/callback'
};

axios.post('/oauth/clients', data)
.then(response => {
    console.log(response.data);
})
.catch (response => {
    // List errors on response...
});

But I am unable to run this example in POSTMAN... I am not sure which function or method is being triggered for above API Call. How can I make use of this POST method outside VueJS.



via Chebli Mohamed

How do we Clear Controller And Model cache in Laravel

I have very simple application in Laravel 5.5.

My Route : Route::resource('books', 'BookController');
My Controller is app/http/Controllers/BookController.php
My Model is app/Book.php

I have similar other modules as well.

INTERESTING PART IS :

My Book controller changes are not being reflected in browser.

I thought of clearing the cache so cleared all caches.

1. Cleared Application Cache > php artisan cache:clear
2. Cleared Route Cache > php artisan route:clear
3. Cleared Configuration Cache > php artisan config:clear 
4. Cleared Compiled Views Cache > php artisan view:clear 

I was not sure which cache was causing the issue so I cleared all. Still my changes are not being reflected in the browser, but when I change the view files, the changes are being reflected.

Any Suggestion please?????



via Chebli Mohamed

Laravel 7 Pagination and Bootstrap Tabs

I've been struggling with this issue for days now.

Basically I use Laravel 7 and Bootstrap tabs called 'All Products' and 'Special Products'.

The problem is: I want to paginate the results, but it doesn't work quite as expected. For example, the initial active tab is 'All Products', if i click page 3 on that tab and switch to 'Special Products' tab, it loads page 3 of that tab as well instead of page 1. I hope this makes sense?

My controller file:

public function index()
    {

        $products = Product::with('brands')->paginate(1,['*'],'products');

        $specials = Product::where([
            ['discount', '!=', null],
            ['discount', '!=', '0']
        ])->paginate(1,['*'],'specials ');

        return view('products.index', ['products' => $products, 'specials ' => $specials ]);

    }

My view file:

<div class="tab-content">
    <div class="tab-pane active" id="allproducts">
        <table class="table table-hover">
            <thead class="text-primary font-weight-bold">
                <th>Product Name</th>
                <th>Brand</th>
                <th>Unit</th>
                <th>Price</th>
                <th>Discount</th>
            </thead>
            <tbody>
                @foreach ($products as $product)
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                @endforeach
            </tbody>
        </table>       

        

    </div>

    <div class="tab-pane" id="specialproducts">
        <table class="table table-hover">
            <thead class="text-primary font-weight-bold">
                <th>Product Name</th>
                <th>Brand</th>
                <th>Unit</th>
                <th>Price</th>
                <th>Discount</th>
            </thead>
            <tbody>
                @foreach ($specials as $special)
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>                                                 
                @endforeach
            </tbody>
        </table>

        

    </div>
</div> <!-- end tab content -->

Can someone guide me please?

Thank you.



via Chebli Mohamed

Unable to get input data from Form submit GET request in laravel 5.1

I have a search form that is sending a GET request to the method that it is using to view the form:

                <form class="form-horizontal" method="GET" action="">
                    <div class="form-group form-group-sm">
                        <div class="col-sm-3">
                            <input type="text" name="inputdate" class="form-control datepicker" placeholder="Date" >
                        </div>
                        <div class="col-sm-2">
                            <button class="btn btn-primary btn-sm btn-block" type="submit">
                                <i class="fa fa-search" aria-hidden="true"></i>
                                Search 
                            </button>
                        </div>
                    </div>
                </form>

And the route:

Route::group(array(
    'middleware' => 'auth',
    'prefix' => '!',
    'namespace' => 'LoggedIn',
    'as' => 'LoggedIn.',
), function() {

    .................

    Route::group(array(
        'prefix' => 'StudentModule',
        'namespace' => 'StudentModule',
        'as' => 'StudentModule.'
    ), function () {

        ............

        Route::group(array(
            'prefix' => 'StudentHomeWork',
            'as' => 'StudentHomeWork.',
        ), function () {

            Route::get('/', array(
                'as' => 'index',
                'uses' => 'StudentHomeWorkController@index'
            ));
        });

    ..................

    });

    ...............
});

And my controller:

public function index()
{
    $searchParam = request('inputdate') ? request('inputdate') : date('Y-m-d');

    echo $searchParam; // this is showing no data
}

The problem is, i couldn't get the data from submitted form. I have used every option that i found in stackoverflow but couldn't get the data. Can anyone point me out what i am missing! My laravel version is 5.1

Note: I am using this method in Laravel 5.8 + 6. Which is working just fine



via Chebli Mohamed

Laravel - Count of items through with belongs to

A company can have many delivery dates. A delivery date may have many entries. The Entry model contains

public function company()
{
    return $this->belongsTo(Company::class);
}

public function delivery_date()
{
    return $this->belongsTo(MgDeliveryDate::class,  'mg_delivery_date_id');
}

What I want is a count of how many entries each delivery date has for each company. For example, something like

$companies = Company->with('delivery_dates', 'delivery_dates.entries')->withCount('delivery_dates.entries')

So if my data was

Company            Delivery Date          Entry Number
   A                   1/2/2020                1
   A                   1/2/2020                2
   A                   2/2/2020                3
   B                   1/2/2020                4

I would get two companies, company A with two delivery dates and a count of 2 for the first date(1/2/2020) and 1 for the second date(2/2/2020) and company B with one delivery date, with an entry count of 1.



via Chebli Mohamed

Laravel validators: prevent submit 2 parameters together

How to prevent presents of 2 parameters that existed in required_without_all validator, ex:

    return [
        'user' => 'required_without_all:customer,public',
        'customer' => 'required_without_all:user,public',
        'public' => 'required_without_all:user,customer',

    ];

How to prevent user from submit 2 keys from above together, ex:

http://127.0.0.1:8000/app/groups-statistics?user=10&customer=10

These are allowed requests:

http://127.0.0.1:8000/app/groups-statistics?user=10
http://127.0.0.1:8000/app/groups-statistics?customer=10
http://127.0.0.1:8000/app/groups-statistics?public=true

Disallowed:

http://127.0.0.1:8000/app/groups-statistics?pubilc=true&customer=10
http://127.0.0.1:8000/app/groups-statistics?user=10&customer=10
http://127.0.0.1:8000/app/groups-statistics?public=10&customer=10


via Chebli Mohamed

How to fix Laravel api update not working?

I want to update a review by ID using the following link in Postman http://localhost:8000/api/v1/reviews/2

I have the following in the ReviewController

public function update(Request $request,Product $product, Review $review)
      {
          $review->update($request->all());
                  // $review->save();
          return response([
              'data' => new ReviewResource($review)
          ],Response::HTTP_CREATED);
      }

When trying to update content for null fields for booktitle and description using PUT method I get a success message however the record remains the same. It is not updated.

This is the review model file

<?php

namespace App\Model;

use App\Model\Product;
use Illuminate\Database\Eloquent\Model;

class Review extends Model
{
    public $timestamps = true;

    protected $fillable = [
    'booktitle', 'description', 'updated_at', 'created_at',
    ];



via Chebli Mohamed

Store array inside of array in db using laravel

I have a common array from request named complemntartData[]. from that array i get some values.i need to store these data in db table field.i used implode function but it shows array to string conversion. this is complementaryData


    if($request->input('complementaryData')){
       foreach($request->input('complementaryData') as $name => $value){
          $data = explode ("_", $name);
          $A = [];
          $B = [];
          if($data[0]=="TextField"){
            $B["id"] = $data[1];
            $A["TextField"] = &$B;
            $B["data"] = $value;
           }
           if($data[0]=="Archive"){
              $B["id"] = $data[1];
              $A["Archive"] = &$B;
              $B["data"] = $value;
           }
           if($data[0]=="MultipleChoice"){
              $B["id"] = $data[1];
              $A["MultipleChoice"] = &$B;
              $B["sub"] = $value;
           }
           $eventParticipants->complementaryData = implode(',',$A);
           //dd($eventParticipants->complementaryData);
        }
   }



via Chebli Mohamed

dimanche 26 avril 2020

Setting active class for menu items dynamically in laravel

I'm creating a laravel application using bootstrap 4.

I have my main navigation menu in app.blade.php . And I have four main blades, About,Product,Contact and Blog.

Then I needed to change the menu item active class according to the current page. As the menu being loaded dynamically from the app.blade.php I had to set the active class for current page in the navigation menu dynamically.

What I did was in every blade I've defined a variable called, $currentpage and assign page name in to it, assume it's blog.blade.php

<?php $currentPage = 'blog';?>
@extends('layouts.app')

@section('content')

and in the app.blade.php,

<li class="<?php if($currentPage =='blog'){echo 'nav-item active';}?>">
                            <a class="nav-link " href=""></a>
                        </li>

So this works properly..

but I want to know Is this the correct way of doing it and what are the other possible ways to fulfill my requirement



via Chebli Mohamed

Laravel multi language option

Currenly i am working a mlm website. Client requirement is When user come to website they can select language. when the click specific language then it will automatically translate language

                        <li>
                        <img class="language-flag" src="/icon/flags/English-flag.svg" alt="">
                        <a href="" title="English" class="language__item" style="background-position:-0px -0px;" data-cf-modified-6443d1b43f4ab48f9fb6cc28-="" data-cf-modified-107c802c5212d7df077f3a9f-="">English</a>
                    </li>
                    <li>
                        <img class="language-flag" src="/icon/flags/Arabic-flag.svg" alt="">
                        <a href="#" title="Arabic" class="language__item" style="background-position:-100px -0px;" data-cf-modified-6443d1b43f4ab48f9fb6cc28-="" data-cf-modified-107c802c5212d7df077f3a9f-=""> Arabic </a>
                    </li>

I want to change language my all app to specific user. Here is the code where user can select language option .



via Chebli Mohamed

How to preserve angular routes when using laravel?

I am new to Laravel, so take it easy on me :)

I have had my Angular 7 application on www.somedomain.com for a year now, but I am at the point of needing a backend framework. The hosting company fully supports Laravel 5.*; therefore, I installed it on the server.

I have made Laravel's default route to point to Angular's index.html like so

Route::get('/', function () { 
    View::addExtension('html', 'php');   
    return View::make('index'); 
});

Now the webpage opens my Angular app successfully, but routes are not the same as they used to.

I manage GUI pages via Angular routes and try to use Laravel routes for Http requests.

My problem is that now www.somedomain.com/about view can be accessed from the Angular app by pressing the navigation button, and in the URL it shows https://ift.tt/2SaanmQ correctly. But when I try to directly access that URL, it shows 500 server error because it is being handled by Laravel.

How can I make sure my GUI routes work without Laravel intervention?



via Chebli Mohamed

How to use get and paginate same time in Laravel

I would like to use paginate. I researched if I use paginate() I have to erase ->get(). but I got error. Could you teach me how to add paginate please?

my current code

$images = ImageGallery::orderBy(DB::raw('LENGTH(wc), wc'))->get()->paginate(5);
        return view('image-gallery2',compact('images'));

blade file code


UPDATE

if I do this

$images = ImageGallery::orderBy(DB::raw('LENGTH(wc), wc'))->get()->paginate(5);

This error

BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::paginate does not exist. 

If I write below

$images = ImageGallery::orderBy(DB::raw('LENGTH(wc), wc'))->paginate(5);
        return view('image-gallery2',compact('images'));

I got this error

Facade\Ignition\Exceptions\ViewException
Call to undefined method App\ImageGallery::links() (View: //resources/views/image-gallery2.blade.php) 


via Chebli Mohamed

how to pass multiple parameters through route using Laravel collective Forms & HTML Addins?

lets assume we have a Delete button inside a form :

 {!! Form::open(['route' => ['posts.destroy','id'=>$post->id], 'method' => 'delete']) !!}
 {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
 {!! Form::close() !!}

i need to pass two or more variables through the Form Route like this:

{!! Form::open(['route' => ['posts.destroy','id'=>$post->id,'title'=>$post->title], 'method' => 'delete']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}

I try to different ways , to take these two parameters but still I couldn't retrieve data

ErrorException in PostController.php line 99:
Missing argument 2 for App\Http\Controllers\PostController::destroy()


via Chebli Mohamed

Ambiguous column name laravel 5.6+

i have a problem with error called "Column 'id' in field list is ambiguous".

I've tried to fix it by using aliases on columns but i had no luck in fixing it. Query looks like this:

SELECT `id`               AS `pf_id`, 
       `id_feature`       AS `pf_if`, 
       `id_feature_value` AS `pf_ifv`, 
       `product_features`.`id_product` 
FROM   `features` 
       INNER JOIN `product_features` 
               ON `product_features`.`id_feature` = 
                  `features`.`pf_id` 
WHERE  `product_features`.`id_product` IN ( 
       33003, 33004, 33011, 33012, 
       33013, 33015, 33016, 33017, 
       33018, 33019, 33020, 33021, 
       33022, 33023, 33024, 33025, 
       33026, 33029, 33030, 33032 ) 
       AND `id_feature` = 5 

Id is used only in select and inner join. It's calling product_features table and features table. Only this pice of code is not working - any other relation on product is working fine. Below are additional info about table structure plus relation:

enter image description here

product_features structure:

enter image description here

features:

enter image description here

Features relation (function from model)

![enter image description here

Thanks for help!



via Chebli Mohamed

Larave 5.2 Session not saving other data

I have a part of my code that saves data in the session and will retrieve my data on the same controller file but cannot access it. Here's how I do it:

public function index(Request $request)
{
    //some process
    \Session::put('data', [
            'recruits' => $recruits, 
            'header'             => $header,
            'condition'          => $condition,
            'sort'               => $sort,
        ]);
    //so when I retrieve it here thru dd(\Session::get('data')), it displays well.
    return redirect()->route('admin.filter');
}
//this is the function which is in the same file
public function filter()
{
    dd(\Session::get('data'));
   // data displayed in my session is only recruits and condition
}

Anyone has idea on this?



via Chebli Mohamed

How to get text Strings order in Laravel project

I would like to sort column like orderBy.

'WC' columns has such data

'AB-1' 'AB-2' 'AB-5' 'AB-300' 'AB-1980' .... etc

Front of "AB-" letter is same. then comes number.

Could you teach me how to write code please?

 public function index()
    {
        $images = ImageGallery::orderBy('wc', 'asc')->get();
        return view('image-gallery',compact('images'));
    }


via Chebli Mohamed

samedi 25 avril 2020

How to give order query when using scorp

I'm trying to get image data. giving order by id desc. I add orderBy sentece after get() it didn't work. Could you teach me how to add order query when using :: scope?

public function index()
    {
        $images = ImageGallery::get()->orderBy('id', 'desc');
        return view('image-gallery',compact('images'));
    }


via Chebli Mohamed

Laravel dynamic routing for search

I would like to generate dynamic route when user clicks on Search button.

I know it can be done with following GET method

https://laravel.dev/search?q=parameter 
https://laravel.dev/search?state=XYZ&category=Automobile

But instead I would like to do following

https://laravel.dev/search/state/XYZ/category/Automobile

So if I add an extra parameter in search form it will just add onto the URL.

The parameters may be optional so can not add a fix route in routes. User may supply category or may not.

How can I achieve that?

Thank you



via Chebli Mohamed

How to return an OUT/INOUT parameter using Laravel + PostgreSQL?

I am using PostgreSQL and Laravel 5 and I could find any resource explaining how to recover the output parameters from DB::statement call of a procedure in PostgreSQL.

I saw people setting cursors.. but is that the only way?

Is that so hard?



via Chebli Mohamed

How to update many db setting values in laravel

1.I have checkboxes data from view.

$data =["name1" =>"value1","name2"=>"value2","name3"=>"value3"]

2.I need to update in controller something like:

Config::update(
          ['id'=>1,"name"=>"name1","value"=>"value1"],
          ['id'=>2,"name"=>"name2","value"=>"value2"],
          ['id'=>3,"name"=>"name2","value"=>"value3"],
       );


via Chebli Mohamed

How to pass optional ID to Laravel Controller from Route?

I want to pass an ID to my controller from Routes:

Route::get('user/{id?}', function ($id= null) {
    return $id;
});

However, I'm not sure where to put the controller name and function?

MyController@get

Laravel's documentation and other questions don't seem to be related to this issue.

What am I missing here?



via Chebli Mohamed

laravel foreach and if else loop errors both in count and variables something

code of 1st error :

@extends('layouts.app')

@section('content')
<h1> posts</h1>
@if(count($posts)>1)

@foreach($posts as $post)

<div class="well">
    <h3></h3>
</div>
@endforeach

@else
<p> no posts found</p>
@endif
@endsection

and image also attached . [enter image description here][1] after i follow the instructions of the chrome this occurs and code will be .. even i have removed the @ and try if() like this .. code 2 ; @extends('layouts.app')

@section('content')
<h1> posts</h1>
@if(count($posts ?? '')>1)

@foreach($posts ?? '' as $post)

<div class="well">
    <h3></h3>
</div>
@endforeach

@else
<p> no posts found</p>
@endif
@endsection

enter image description here

[1]: https://i.stack.imenter code heregur.com/21weC.png



via Chebli Mohamed

Slow photo loading in Laravel

I have Laravel code below in my project on local machine and running it on development mode. Photos are stored in public folder. In current example I have 17 photos in mobile_photos folder, the weight of all of them is 572kB. The problem is slow loading of mentioned images even they are not heavy, exact time you can find on photo below. I expected to load these ptohos in ms but as you can see loading time for one photo is more then more then 1s. Any idea how to fix this problem?

  <link rel="stylesheet" href="/css/justifiedGallery.css" />       
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script type="text/javascript" src="/js/jquery.justifiedGallery.js"></script>

    <div id="basicExample" class="justified-gallery">
    @foreach ($photo as $photo)                       

    <a href="">
    <img alt="caption for image" src=""/>
    </a>  
    @endforeach     
    </div>

  <script>
        $( document ).ready(function() {                
            $("#basicExample").justifiedGallery({
                rowHeight : 120,
                lastRow : 'justify',
                margins : 3                    
            });           
        });          
   </script>

enter image description here



via Chebli Mohamed

Getting Token expired for all json post requests

I am passing token in all the headers but it only works for login, after that for all requests it says "Token Expired"

Token Setup :

enter image description here

enter image description here

Output in Result tree :

enter image description here

Also when I look at my website, I can see 2 tokens :

<!-- CSRF Token -->
<meta name="csrf-token" content="AqrfjMcG1adWWDlx8YYkYqOCy3Mwp7fRynwut222">


<input type="hidden" name="_token" value="AqrfjMcG1adWWDlx8YYkYqOCy3Mwp7fRynwut222">

So I am passing _token for all request headers as above both has same content/value.

I am also not sure about x-socket-id, It came be default as I recorded script. is it ok to remove it?



via Chebli Mohamed

Send CSV file as Email attachement in Laravel

I am working on Laravel file attachment. I have successfully generated a .pdf file and sent as attachment in mail. Now I have to send CSV file as attachment in mail with Laravel. When I click the submit button it just download the file rather then to send an email.

Controller Code:

$data["email"] = $request->recipient_email;
$data["subject"] = 'Cashup Report for '. $venue->name;
$data["bodyMessage"] = $venue->name.' from '.$start.' to '.$end ;

 $excel = Excel::create(uniqid().'Cashups', function($excel) use($transactions,$start,$end,$venue) {
                        $excel->sheet('New sheet', function($sheet) use($transactions,$start,$end,$venue) {
      $sheet->loadView('excel.cashups', array('transactions' => $transactions, 'start'=> $start, 'end' => $end, 'venue' => $venue));
            });
 });

     //Feedback mail to client
 Mail::send('emails.cashups_report', $data, function($message) use ($data,$excel){
    $message->from(config('mail.from.address'));
    $message->to($data["email"]);
    $message->subject($data["subject"]);
    //Attach PDF doc
    $message->attachData($excel->output(),'cashups-report.xlsx');
});

I dont know where i am going wrong. I would appreciate if someOne Guide me through this. Thanks



via Chebli Mohamed

is there anyway to remove laravel telescope database without running another migration?

I have completely removed this package from my project but the databases still there, is another way to remove them too?



via Chebli Mohamed

vendredi 24 avril 2020

Property [categories] does not exist on this collection instance. (View: D:\xampp\htdocs\olshop\resources\views\backend\product\index.blade.php)

this is my Model

//relation from model products to model categorys
public function categorys()
{
    return $this->belongsTo('App\Category');
}

 //relation from model products to model categorys
public function categorys()
{
    return $this->belongsTo('App\Category');
}

this is my controller

 public function index()
{
    //controller buat manggil foreachnya
    $data['title'] ='Product';
    $data['page'] = 'Semua Product';
    $data['products'] = Product::all();
    return view('backend.product.index', $data);
}

**this is my **

                @foreach($products->categorys as $key => $value)
                <tr>
                    <!-- view bladenya  -->
                    <td></td>
                    <td></td>
                    <td></td>

I am trying to using $products->$categorys but its gone wrong



via Chebli Mohamed

If output of \Log::info depens on some options?

If output of

 \Log::info('text');

function is dependable on some options ?

in .env I have :

APP_DEBUG=false

and in config/app.php

'debug' => env('APP_DEBUG', false),

Also in config/logging.php I have options(seems default):

<?php

use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [


    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['daily'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 14,
        ],

        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'Laravel Log',
            'emoji' => ':boom:',
            'level' => 'critical',
        ],

        'papertrail' => [
            'driver' => 'monolog',
            'level' => 'debug',
            'handler' => SyslogUdpHandler::class,
            'handler_with' => [
                'host' => env('PAPERTRAIL_URL'),
                'port' => env('PAPERTRAIL_PORT'),
            ],
        ],

        'stderr' => [
            'driver' => 'monolog',
            'handler' => StreamHandler::class,
            'formatter' => env('LOG_STDERR_FORMATTER'),
            'with' => [
                'stream' => 'php://stderr',
            ],
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

];

The quesion is that with my options on live server I expected

 \Log::info('text');

would not log lines, but it writes lines anyway.

I read here https://laravel.com/docs/5.7/logging do not see any dependencies.

? Laravel 5.7

Thanks!



via Chebli Mohamed

Firebase receive notification while tab is active or on focus

What i want is to be able to perform an action when a user receives a notification while the browser is open and tab is active or focused. I can seem to figure out a way to receive notification or perform am action while browser tab is open or focused, It works well when browser is at the background.I upgraded to firebase version 7.8.0 and below is the code am using

     <script>
    // Your web app's Firebase configuration
  var firebaseConfig = {
   apiKey: "xxxx",
   authDomain: "xxx",
   databaseURL: "xxxxx",
   projectId: "xxxx",
 storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx"
};
 // Initialize Firebase


  if (!("Notification" in window)) {
   console.error("Notification isn't enabled");
   } else if (Notification.permission === "granted") {
   console.log("Notification is enabled");
   } else if (Notification.permission !== "denied") {

  // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 firebase.initializeApp(firebaseConfig);
 const messaging = firebase.messaging();

messaging.onMessage((payload) => {
 console.log('Message received. ', payload);
 // ...
 });

  messaging
  .requestPermission()
  .then(function () {
    // MsgElem.innerHTML = "Notification permission granted." 
    //console.log("Notification permission granted.");

     // get the token in the form of promise
      return messaging.getToken()
     })
    .then(function(token) {
    // print the token on the HTML page
   //TokenElem.innerHTML = "token is : " + token
         $.ajax({
        type:'POST',
        url:'/SaveNotificationToken',
        data:{token : token, _token: "<?php echo csrf_token(); ?>",UserId:     },
             success:function(data){
            //alert(data+"You will receive notiications from clients that viewed your service ");
            $("#msg").html(data);
        }
     }); 

   })
  .catch(function (err) {
   //ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
   console.log("Unable to get permission to notify.", err);
     });

 }


 </script>


via Chebli Mohamed

How to adjust column Width in Laravel form-group

Here is simple contact form. Left side column display question that is "x1-question" and Right side is text field that User type answer.

I would like to controll Left side width size by changing like ...type class="col-sm-5" or sm- 4. but I couldn't adjust what I want width size and it become big slip and view become really ugly.

Could you teach me right col-xx-x code in Laravel form-group please?

Currently when I type long texst question Left side(question part) this is really narrow. i would like to it to more wide.

my Laravel Framework is 6.18.8

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="" rel="stylesheet">
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

<div class="container">
    <div class="row">
        <div class="col-xl-12">
            <div class="panel panel-default">

         <div class="form-group">
     <p>   {!! Form::label('x1', 'x1-question', ['class' => 'col-sm-2 control-label']) !!} </p>

        <div class="col-sm-10">
            {!! Form::text('x1', null, ['class' => 'form-control']) !!}

            @if ($errors->has('x1'))
                <span class="help-block">
                    <strong></strong>
                </span>
            @endif
        </div>
    </div>  


via Chebli Mohamed

Which Laravel Passport Grant Type is perfect for 3rd Party server accessing my application resources using an API?

Basically, I would like to give 3rd Party (few X companies) access to my resources using an API and I would like to know which Grant Type would be best suitable and why?

I have already implemented "Client Credential Grant Type" which seemed perfect as it is best used for Machine to Machine interaction and that's what I wanted to do, that is, give 3rd Party Company access using an API to fetch and send data, but the problem with this Grant Type is that, I am unable to make a link with Users Table because there is no user_id. so, It is not possible for me to keep track of which X company is sending or fetching data. Which makes me question if I am using the right Grant Type?

I have already followed first few steps from Laravel Passport Documentation (https://laravel.com/docs/7.x/passport) to setup Passport in my application and everything seems to be good.

Steps Followed

1. composer require laravel/passport
2. php artisan migrate
3. php artisan passport:install
4. add the Laravel\Passport\HasApiTokens trait to your App\User model.
5. call the Passport::routes method within the boot method of your AuthServiceProvider
6. Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport.

There are 4 types of clients:

1. php artisan passport:client --public   (for SPA or JS application)
2. php artisan passport:client --client   (for machine to machine)
3. php artisan passport:client --personal (for mobile applications)
4. php artisan passport:client --password (outdated)

Which is the right passport:client? and how to implement it?



via Chebli Mohamed

Laravel auth nothing happen when trying to login with default laravel auth page

I have previously transferred laravel from server to another by copying the laravel project folder, now when i try to login using default laravel auth page , if i enter wrong auth value i get error auth.failed but when i enter a valid auth value the page refresh but nothing happen. I notice from browser view source the value of CSRF token is changing one i enter the valid auth value

I tried to delete the session files /storage/framework/sessions and tried

php artisan view:clear

php aritsan cache:clear

but nothing happen. How can i fix this issue.



via Chebli Mohamed

Verify User Token in Laravel

I have an ionic 3 application that is using laravel as backend . For auth I am using JWT and everything is working fine from registration , login and posting data within the app.

Problem starts when the user closes the mobile app and opens it again, I want the app to auto login the user using the saved token in storage.

The code below is for checking if the user has a token in storage, if there is then the token needs to be sent to laravel backend for verification.

verifyToken() {
    return new Promise((resolve, reject) => {
      this.storage.get("token").then((value) => {
        let headers = new Headers();
        headers.append("Accept", "application/json");
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", "Bearer " + value);
        this.http.post(ApiUrl + "/verifyToken", { headers: headers }).subscribe(
          (res) => {
            let data = res.json();
            console.log("Valid token results:", data);
            resolve(data);
          },
          (error: any) => {
            console.log("Token was invalid", error);
            reject(JSON.parse(error._body));
          }
        );
      });
    });
  }


On Laravel backend I have this code for verification

 public function verifyToken()
    {
        try {

            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return response()->json(['success' => false, 'error' => 'User not found.',$e->getStatusCode()], 404);
            }

        } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

            return response()->json(['success' => false, 'error' => 'Login Token expired.',$e->getStatusCode()], 401);

        } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

            return response()->json(['success' => false, 'error' => 'Login Token invalid.',$e->getStatusCode()], 401);

        } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

            return response()->json(['success' => false, 'error' => 'Login Token not supplied.',$e->getStatusCode()], 401);

        }

        // the token is valid and we have found the user
        return response()->json(['success' => true, 'message' => 'Token is valid.'], 200);

    }

When I test this via postman and provide valid user token, I get status 200 but when I do the same on the mobile app I get an error 500

"message": "The token could not be parsed from the request",
"exception": "Tymon\JWTAuth\Exceptions\JWTException",.

enter image description here



via Chebli Mohamed