Laravel: Best practice for inline PHP in a blade file

3.6k Views Asked by At

So I have the following blade file:

confirmEmail.blade.php

@extends('layouts.master')

@section('title')
{{ trans('tc.signUpConfirmTitle')}}
@endsection





@section('body')


<div class="container">
  <div class="row">
    <div class="col-lg-4">
      &nbsp;
    </div>

    <div class="col-lg-4">

      <?php
      echo $_GET['emailToken'];
      $emailToken = isset($_GET['emailToken']) ? $_GET['emailToken'] : "";
      $email = isset($_GET['email']) ? $_GET['email'] : "";

      //database lookup:
      $user = User::where('email','=',$email)->first();   //this fails...

      if($user->emailToken == $emailToken){
        echo "OK!";
      }
      ?>




      <br><br><br><br><br><br>

    </div>

    <div class="col-lg-4">
      &nbsp;
    </div>

  </div>
</div>

@endsection

As you can see, I have some raw PHP between <?php ?> tags. The problem is that User::where(...) is failing ("FatalErrorException" - Class 'User' not found).

I guess this is because I need to do some Laravel import? But is doing this lightweight?

Can I ask what the best practice would be in this my case? I'm still very new to Laravel so bear with me. Is using raw PHP like this defeating the whole purpose?

I've been using Blade templates for spitting out simple variables and parameters fine up until now. But I want to do something a little more complicated now and I'm having trouble.

1

There are 1 best solutions below

3
On BEST ANSWER

Is using raw PHP like this defeating the whole purpose? Exactly ! MVC are made so that there will be different layers of different type of jobs "Model,View and Controller" here in your case you are combining the job of controller into a view and hence diminishing the role of controller.

The following code in your controller will do what you are trying to do. Lets say you have a function named confirmation which is responsible for all the validation and returning the response accordingly.

public function confirmation(Request $request)
{
   $status = 'Failure';
   $emailToken = $request->emailToken;
   $email = $request->email;
   if(isset($email))
     {
       $user = User::where('email','=',$email)->first();
        //I do not know why this fails on your side check if you have that email in your database
       if($user->emailToken == $emailToken)
        {
          $status = 'Success';
        }
     }
          return view('confirmEmail')->with('message', $status);
}

You should not add confirmation key into users table however its your db table you can insert anything anywhere but my suggestion is you should create a separate table for that.