samedi 28 avril 2018

Laravel use view while sending email from Gmail API

I am trying to send emails using Gmail API. It worked fine if I use raw body, but I am unable to figure out how to use Laravel Views as the body when sending the email from Gmail API . Or use Gmail API to send using Laravel Mail Here is my code:

        $strSubject = 'Test mail using GMail API';
        $strRawMessage = "To: Someone <someone@domain.com>\r\n";
        $strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
        $strRawMessage .= "MIME-Version: 1.0\r\n";
        $strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
        $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
        $strRawMessage .= "this is body";
        $service = new Google_Service_Gmail($client);

        try{
            $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
            $msg = new Google_Service_Gmail_Message($client);

            $msg->setRaw($mime);
            $service->users_messages->send("me", $msg);

        }
        catch(Exception $e){
            \Log::info($e->getMessage());

        }



via Chebli Mohamed

Laravel eloquent: Multiply two columns of two different tables and display

Carts table columns :

    'id',
    'user_id',
    'sp_id',
    'service_id',
    'dryclean',
    'q_Shirt',
    'q_Pant',
    'q_Tie'

Pricing table column :

'id'
'sp_id'
'Shirt'
'Pant'
'Tie'

Both table do not have any relationship defined.

In cart controller

public function cart($sp_id, $service_id)
    {
     $prices = DB::table('pricings')->where('pricings.sp_id', '=', $sp_id)->get();
     $cart = DB::table('carts')->where('carts.service_id', '=' , $service_id)->where('carts.sp_id','=', $sp_id)->where('user_id', '=' , auth()->id())->orderBy('id', 'desc')->take(1)->get();
     return view('user.cart')->with('prices', $prices)->with('cart', $cart);
    }

How do I calculate total amount of order?

If column dryclean has value of none then total is 0. else total will be

(
carts->q_Shirt*prices->Shirt +
carts->q_Pant*prices->Pant +
carts->q_Tie*prices->Tie
) 

This code is just for understanding of how I am calculating total

Please help me write code in laravel controller to calculate total and how to display it in view.



via Chebli Mohamed

Admin log in Laravel - redirecting to user login page

Im trying to set up multiple authentication, and have a login for admins as well as users. I followed part 1 and got two half way through of part 2 of this tutorial https://www.youtube.com/watch?v=gpACQXVX2kA&t=32s. When I try to log in as an admin, it redirects to /login (users login page) when I have it set to redirect to /admin/home.

It is redirecting like that because the admin login details are not correct? I set up the admin details through the database but in the video it says to copy and paste the encrypted password from the users table, so I did, and used the same password as that user to sign in.

I watched the video over and over again for any mistakes following along, but I don't think I done anything differently.

There is a lot of files I created and edited to try get this to work, so If you need to see anymore please let me know.

web.php

Route::get('admin/home','AdminController@index');
Route::get('admin','Admin\LoginController@showLoginForm')->name('admin.login');
Route::post('admin','Admin\LoginController@login');
Route::post('admin-password/email','Admin\ForgotPasswordController@sendResetLinkEmail')->name('admin.password.email');
Route::get('admin-password/reset','Admin\ForgotPasswordController@showLinkRequestForm')->name('admin.password.request');
Route::post('admin-password/reset','Admin\ResetPasswordController@reset');
Route::get('admin-password/reset/{token}','Admin\ResetPasswordController@showResetForm')->name('admin.password.reset');

AdminController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function index()
    {
        return view('admin.home');
    }
}

admin.php

<?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

LoginController

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = 'admin/home'; //user redirects to /routes


    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']); 
    }

    public function showLoginForm()
    {
        return view('admin.login');
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }
}

Login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Admin Login</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="">
                        

                        <div class="form-group">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="" required autofocus>

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

                        <div class="form-group">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

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

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" > Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Database structure database-structure

Database content (copied password) database-content



via Chebli Mohamed

Laravel migration cancel column as nullable

I created a migration with user_id column making nullable. How can I change user_id as not nullable? My previous migration code is given below:

Schema::table('users', function($table)
{
    $table->string('name', 50)->nullable();
});



via Chebli Mohamed

Method in model doesn't seem to be being recognised in view

I was tidying up my code. Instead of having my logic all in the views, I broke it off into functions in the Tenancy model, and called them in the view.

For example

This was my original line in index.blade.php

@if($Tenancy->accepted == 0 && $Tenancy->request_sent != 1)

I changed it to this

@if($Tenancy->addTenancy()

And moved the logic to my Tenancy model like so

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

This works for adding a user.

But for detecting requests, and detecting friends it is not working. The IF is't progressing past the first if.else block

 @if(Auth::user()->id == $user->id)
          <h1>You cannot add yourself</h1>
        @elseif($Tenancy->addTenancy())
          <a href="/account/tenancy//create" class="btn btn-primary">Start Tenancy</a>
        @endif

          <!-- 
            If the user signed in, isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->

        @if(Auth::user()->id == $user->id)
          <!-- 
            If the request has been sent, but hasn't been accepted.
            Give option to accept and reject.
            This updates the values in DB.
          -->
          @if($Tenancy->hasRequestPending())
            <form method="POST" action="/account/tenancy//accept">
              
              <input type="submit" class="btn btn-primary" value="Accept Request">
            </form>
            <form method="POST" action="/account/tenancy//reject">
              
              <input type="submit" class="btn btn-warning" value="Reject Request">
            </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
          @elseif($Tenancy->isTenancy())
            <form method="POST" action="/account/tenancy//end">
              
              <input type="submit" class="btn btn-primary" value="End Tenancy">
            </form>
            <h5>Currently in Tenancy with </h5>
            <h5>Your property is </h5>
          @endif <!-- End of current user vs this user-->
        @endif <!-- Initial If-->

Correlating functions in Tenancy Model

public function hasRequestPending()
    {
        return $this->accepted == 0 && $this->request_sent == 1;
    }

    public function inTenancy()
    {
        return $this->accepted == 1 && $this->request_sent == 0;
    }



via Chebli Mohamed

Auth::login doesnt work

I want to modify the login compartment of laravel, I want to do everything the same without encrypting the password.

This is the model:

class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array*/

protected $fillable = [
    'id','nombre', 'apellido1', 'apellido2',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

protected $table = 'usuario';
}

I modify LoginController overwritten the login function:

  public function login(Request $request)
 {
    $this->validateLogin($request);

    $email = $request->get('email');
    $pass = $request->get('password');

    $matchWhere = ['email' => $email, 'password' => $pass];

    $user = User::where($matchWhere)->first();

    if ($user ) {
        Auth::guard('usuarios')->login($user);

        return redirect()->intended('/home');
    } else {
        return $this->sendFailedLoginResponse($request);
    }
}

And I create the specific guard in auth.php:

 guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

    'usuarios' => [
        'driver' => 'session',
        'provider' => 'usuarios',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'usuarios' => [
        'driver' => 'database',
        'table' => 'usuario',
    ],
],

Finally I modify the app.blade.php using my own guard:

@if (Auth::guard('usuarios')->guest())
 <li><a href="">Login</a></li>
 <li><a href="">Register</a></li>
@else
  -- logout
@endif

Why doesn't work? I modified the provider to eloquent and change the model. I try to use the default provider



via Chebli Mohamed

Attempting to clean up code -> errorexception must return a relationship instance

I'm trying to clean up code in my view so removing the logic, and calling a method instead.

This was my original line in index.blade.php

@if($Tenancy->accepted == 0 && $Tenancy->request_sent != 1)

I changed it to this

@elseif($Tenancy->addTenancy)

And moved the logic to my Tenancy model like so

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

I'm not looking for a relationship. Any idea about this error.



via Chebli Mohamed