vendredi 1 mai 2020

Laravel 7 HTTP Client - Unable to send POST request with `body`

Using Laravel 7.6 and it's built-in HTTP Client.

I'm trying to send a simple POST request with body in Raw JSON format to my other domain but no luck:

$response = Http::post('https://example.com', [
    'body' => '{ test: 1 }'
]);

I get 400 Bad Request - Client error - because my server expects body as a mandatory.

What am I missing here?



via Chebli Mohamed

Laravel app logging out authenticated user when redirecting (it shouldn't)

I have created a method that logs a user into our site via a link from a separate website. We use a token and username to find the user, then use the built in login method to authenticate them (I can confirm this all works as expected).

Here is the function:

public function login($username, $token, $redirect)
{
    $accountLogin = AccountLogin::Where('username', $username)
        ->Where('token', $token)
        ->first();

    if ($accountLogin) {
        try {
            Auth::login($accountLogin);
            print_r(Auth::check()) // prints 1.
            header('Location: ' . $redirect);
            exit;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    echo(array(
       'status' => 'error',
       'message' => 'Error logging in'
    ));
}

My problem is that the user seems to be logged out after the redirect.

Within the function above I can see the the account is found, and Auth::check() returns 1 or if I echo out Auth::User() then I do get the users info.

We then attempt to do a redirect which should take us to the route passed in as a parameter (you do need to be authenticated for all these routes) but instead I am redirected to the home page and logged out. If I log in from that page then it takes me to the url I wanted to reach originally (so it's like it is remembering where I want to go, but just doesn't recognise that I'm logged in).

Both sites are currently running locally via apache.

TIA.



via Chebli Mohamed

Changing the index blade in laravel issue

I have following in my laravel web.php

Route::get('/', function () {
        return view('home');
    })->middleware('auth');

    Route::get('/home', 'HomeController@index');

This would redirect my users back to login page if they are not logged in and logged in users would redirect to home page.

Now In my home controller index function I have following code,

public function index()
    {
        $get_customers = User::where('user_roles','=','customer')->get();
        $count_customers = $get_customers->count();

        $get_apps = Website::all();
        $count_apps = $get_apps->count();
        return view('home',compact('count_customers','count_apps'));
    }

When every time i'm trying to access my home page after logged in i'm getting an error saying

$count_apps is undefined

BUT,

When I used following routing in my web.php instead of previous routing, home page gives no error and works properly

Route::get('/', function () {
     return view('auth.login');
 })

But even though this made my login blade as the index page, every time when I try to access index as an already logged in user it keep redirecting me to the login blade not to he home blade....

How can I fix this issue?



via Chebli Mohamed

how to show user name with id from 2 tables in laravel

when i send a letter, i catch sender_id with auth()->user()->id and save into the letter table

but just user_id will save, like 2 or 3 ...

how can i show user name in my view ?

list.blade.php :

<tr>
     <td></td>
</tr>

LetterController.php -> public function index :

$letters = Letter::latest()->paginate(10)->where('recieve_id', '=', auth()->user()->id);

LetterController.php -> public function store :

Letter::create([
    'sender_id' => auth()->user()->id,
]);

letter table :

$table->string('sender_id');

and i have a relation but i dont know it is correct or not

Letter.php :

public function user()
{
    return $this->belongsTo(User::class, 'id', 'sender_id');
}

User.php:

public function letter()
{
    return $this->hasMany(Letter::class);
}

UPDATE :

in veiw when use this :

<td></td>

but i have this error :

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.sender_id' in 
'where clause' (SQL: select * from `users` where `users`.`sender_id` = 1 limit 
1) (View: D:\Web\Projects\automation\resources\views\Letter\list.blade.php)


via Chebli Mohamed

distinct() on specific column is not working in laravel?

I am trying to get rows where rate_card_id is different but is not working.

 $distinct_rows = RateCharge::where('customer_charge_id',$customer_charge_id)->distinct('rate_card_id')->get();

it is fetching all the rows where customer_charge_id matched.



via Chebli Mohamed

is there any rewrite rule to map laravel's /public/ directory with its prevoius directory?

I am refering few website for references,

https://laracasts.com/discuss/channels/laravel/wordpress-and-laravel-on-subfolder?page=1

htaccess to allow laravel site inside of wordpress

Basically, I have placed a laravel directory inside a wordpress.

https://exmapledomain.com  -> Wordpress Directory
https://exampledomain.com/demo -> laravel directory

the folder structure is like this

/var/www/html/exampledomain/web    : Wordpres
/var/www/html/exampledomain/web/demo : laravel

from different refrences, i have placed a .httaccess file inside demo(laravel )

cat /var/www/html/exampledomain/web/demo/.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

now when i type : https://exampledomian.com/demo, it gives me 404 ( this 404 comes from laravel because its cant go to public, but if i type https://exampledomain.com/demo/public , it works fine



via Chebli Mohamed

Send email verification code to another base_url in laravel

I have two laravel systems and both connected to one master database

1.customer portal-customer.test
2.admin portal - admin.test

Customers are not allowed to access to the admin portal

But admin can create customers from admin dashboard.

Customers cannot' login to their profile until they verify their email.

Currently if an user creates an account directly through the customer portal, the user receive the verification email and if he/she clicks on the link with in 60 minutes, account get verified and activated.

verification link look like this:

http://customer.test/email/verify/13/976bdd188ad675ad87c827ca9723fb4a7bda2178?expires=1588242534&signature=cc628ef025eb7cd03fe76093be1e9e3fdfce12f5208c185560d1996b9f662744 

But now when the admin creates an user account for a customer through the admin panel(admin.test)same process need to be happened.

Following is my user create function in the 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));
        //$user->notify(new SendRegisterMailNotification());

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

Here also user create successfully, email also send to the user's email BUT the issue is verification link's base url.... it has to be, customer.test but it inclludes admin.test.....So now when ever a user clicks on that link it'll take customer to a link like,

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

As the customers are not allowed to admin panel user gets a 403 forbidden message..

So how can I change this Base url???

event(new Registered($user));

handles the email sending once when the user is being created..



via Chebli Mohamed