jsartisan

jsartisan

Member Since 4 Years Ago

Experience Points 8,045
Experience Level 2

1,955 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 147
Lessons
Completed
Best Reply Awards 1
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

24 Oct
2 years ago
27 Sep
2 years ago

jsartisan left a reply on Error Exception Email In Laravel

You can also use this Github repo for emailing the errors with full stack trace.

24 Sep
3 years ago

jsartisan left a reply on Auth Login State Not Persisting

somebody please help !

jsartisan started a new conversation Auth Login State Not Persisting

Hi guys, i'm trying to authenticate user from facebook. Facebook returns the data and a column is added in database. When auth::check after it , it returns true . But after redirecting to the homepage, the state is persisting. Auth::check then return false everywhere.

Here is my authenticate

Authenticate.php

use Illuminate\Contracts\Auth\Guard;
use Laravel\Socialite\Contracts\Factory as Socialite;
use Lenro\Repositories\DbUserRepository;
use Auth;


class  Authenticate {

    /**
     * @var DbUserRepository
     */
    private $userRepo;
    /**
     * @var Socialite
     */
    private $socialite;
    /**
     * @var Guard
     */
    private $auth;


    /**
     * Constructor method for the class
     *
     * @param DbUserRepository $userRepo
     * @param Socialite $socialite
     * @param Guard $auth
     */
    function __construct(DbUserRepository $userRepo, Socialite $socialite, Guard $auth)
    {
        $this->userRepo = $userRepo;

        $this->socialite = $socialite;

        $this->auth = $auth;
    }

    /**
     * Method to authenticate
     *
     * @param $driver
     * @param $hasCode
     * @param AuthenticateUserListener $listener
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function execute($driver, $hasCode, $listener)
    {   

        if( !$hasCode) return $this->getAuthorizationFirst($driver);

        $userData = $this->getSocialUser($driver);

        $user = $this->userRepo->findByEmailOrCreate($userData);

        $this->auth->login($user); 

        \\ dd($this->auth->check()); ====> this returns true always

        return $listener->redirectTo('/', $user);

    \\ after redirecting, auth::check returns false in view and everywhere
    }
06 Sep
3 years ago

jsartisan left a reply on How To Use Where Conditions For Relation's Column

Try this

    $contracts = App\Contract::with(['customer' => function ($query) {
         $query->where('email', '!=', '');

    }])->get();
29 Aug
3 years ago

jsartisan left a reply on Two Validators For Save And Publish

you can use something like this. based on the type of request. you can specify the rules.


public function rules()
    {
        $request = Request::instance();

        switch($request->method())
        {
            case 'GET':
            case 'DELETE':
            {
                return [];
            }
            case 'POST':
            {
                return [
                    'password'              => 'required|min:6',
                    'email'                 => 'required|email|min:5|unique:clients',
                    'first_name'            =>  'required',
                    'last_name'             => 'required',
                ];
            }
            case 'PUT':
            case 'PATCH':
            {
                $student = Student::find($request->input('student')['id']);

                return [
                    'full_name'             => 'required|min:8',
                    'address'               => 'required|min:5',
                    'year_of_passing'       => 'required',
                    'email'                 => 'required|email|min:5|unique:students,email,' . $student->id . ','
                ];
            }
            default:break;
        }
    }

i used this in a student management app.

28 Aug
3 years ago

jsartisan left a reply on Check Another Field When Authenticating User

suppose post_login is the function that is handling the post request of login page.

then the code will be like this:


public function post_login()
{   
    $inputs = Request::all();
    Auth::attempt(['email' => $inputs['email'], 'password' => $inputs['password'] ,'active' => 1 ]))
        {
           \\ active user is logged in now . do whatever you want to do with the logged in user. redirect him to somewhere or anything
        }
}

jsartisan left a reply on Check Another Field When Authenticating User


if ($this->auth->attempt(['email' => $clientData['email'], 'password' => $clientData['password'] ,'active' => 1 ]))
        {
           \\ active user is logged in now
        }

jsartisan left a reply on L4 Login Problems

@lstables check for filter. there might be a filter on that route.

jsartisan left a reply on BadMethodCallException In Validator.php - Method [validateRequred] Does Not Exist.

Try this.

namespace App\Http\Controllers;

use App\Article; use Request; use Illuminate\HttpResponse; use App\Http\Controllers\Controller;

class ArticlesController extends Controller { public function index() { $articles = Article::latest('publish_at')->published()->get();

    return view('articles.index', compact('articles'));
}

public function show($id)
{
    $article = Article::findOrFail($id);
    
    return view('articles.show', compact('article'));
}

public function create()
{
    
    return view('articles.create');
}

public function store(Request $request)
{
    
    Article::create($request->all());
    
    return redirect('articles');
    
}

}

jsartisan left a reply on Populating Select Menu From Model In User Registeration Form

This code should work now and please reply fast.

yourschoolcontroller.php


\\ this is the function that return view of your register page
function register(){
    $schools = App\School::all();
    
    return view('register',compact('schools');
}

register.blade.php

<select name="parent_id" class="form-control">
        <option value="" selected disabled style="display:none">choose your school</option>
        @foreach ($schools as $school)
            <option value="{{ $school->short_name }}">{{ $school->name }}</option>
        @endforeach
    </select>

jsartisan left a reply on Photo Upload Preview

You don't need the save button now. the php and js i pasted updated the database and uploaded the image in uploads folder.So there is no point of using the save button.

jsartisan left a reply on Populating Select Menu From Model In User Registeration Form

if this gives error. Then your schools table must be empty then.

jsartisan left a reply on Populating Select Menu From Model In User Registeration Form

try this.

<?php $schools = \School::all(); ?>
<select name="parent_id" class="form-control">
        <option value="" selected disabled style="display:none">choose your school</option>
        @foreach ($schools as $school)
            <option value="{{ $school->id }}">{{ $school->name }}</option>
        @endforeach
    </select>

jsartisan left a reply on Photo Upload Preview

try {!! Form::model($user, ['route' => ['profile.update', $user->username], 'method' => 'PATCH', 'files'=>true,'id' => 'upload' ]) !!}

jsartisan left a reply on Populating Select Menu From Model In User Registeration Form

change {{ $schools = \School::lists() }} to {{ $schools = App\School::lists() }}

jsartisan left a reply on What Is The Site That Is Like Composer But Deals With CSS And Things Like Jquery?

@jasonb try to avoid bower. I once used it for angular. It gave me different versions of each dependencies and i was pulling my hair out because i could n't figured it out what i did wrong. Something bower don't maintain latest version and it might cause problems. :)

jsartisan left a reply on Populating Select Menu From Model In User Registeration Form

@mezie change the name of the function as list is a reserved keyword in php. Make and use it like 'lists' instead of 'list'.

jsartisan left a reply on Populating Select Menu From Model In User Registeration Form

try this.



namespace App;

use Illuminate\Database\Eloquent\Model;

class School extends Model
{
    public static function lists()
    {
        return static::all()->pluck('id', 'name');
    }
}

{{ $schools = \School::lists() }}
<select name="parent_id" class="form-control">
        <option value="" selected disabled style="display:none">choose your school</option>
        @foreach ($schools as $school)
            <option value="{{ $school->short_name }}">{{ $school->name }}</option>
        @endforeach
    </select>

jsartisan left a reply on Populating Select Menu From Model In User Registeration Form

@mezie @oes You can't use list as a function. list is reserved keyword in php. use lists instead of list

jsartisan left a reply on Complicated Relationship

@phildawson This is exactly what is explained in that video :) :D

jsartisan left a reply on Photo Upload Preview

If you still have any doubt.Let me know

jsartisan left a reply on Photo Upload Preview

I'll explain this in steps.

  1. Include this js after your jquery in your header or footer - . http://malsup.github.io/min/jquery.form.min.js
  2. Now in your form. Assign some id to your form and to your file input tag. ( #upload for Form and #image for my input file tag in my case ).
  3. Copy the following js in your js file or script.
/*
|------------------------------------------------------------------------
| USER AVATAR UPLOAD
|------------------------------------------------------------------------
*/

$(document).ready(function() {
   var options = { 
    beforeSubmit:  showRequest,
    success:       showResponse,
    dataType: 'json' 
    }; 
    
    $('#image').change(function(){
        $('#upload').ajaxForm(options).submit(); 
    });

}); 

function showRequest(formData, jqForm, options) { 
    
   $("#validation-errors").hide().empty();
   
   return true; 
} 

function showResponse(response, statusText, xhr, $form)  { 
   if(response.success == false)
   {
       var arr = response.errors;
       $.each(arr, function(index, value)
       {
           if (value.length != 0)
           {
               $("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
           }
       });
       $("#validation-errors").show();
   } else {
    // this will preview your uploaded file
       $("#user-profile").attr('src',response.file);
   }
}
  1. Copy the following php for your controller for the route you defined in the Form facade( profile.update in your case )

     $file = Request::file('image');

       $destinationPath = 'uploads/'; // make sure this folder has 777 permission

        $filename = $file->getClientOriginalName();
        
        $file->move($destinationPath, $filename);

        // save the file path on user avatar

        $user = User::where('id',$user->id)->first();

        $user->avatar = $destinationPath.$filename;

        $user->save();
        
        return response()->json(['success' => true, 'file' => asset($destinationPath.$filename) ]);

jsartisan left a reply on Photo Upload Preview

main.js

/*
|------------------------------------------------------------------------
| USER AVATAR UPLOAD
|------------------------------------------------------------------------
*/

$(document).ready(function() {
   var options = { 
    beforeSubmit:  showRequest,
    success:       showResponse,
    dataType: 'json' 
    }; 
    
    $('#image').change(function(){
        $('#upload').ajaxForm(options).submit(); 
    });

}); 

function showRequest(formData, jqForm, options) { 
    
   $("#validation-errors").hide().empty();
   
   return true; 
} 

function showResponse(response, statusText, xhr, $form)  { 
   if(response.success == false)
   {
       var arr = response.errors;
       $.each(arr, function(index, value)
       {
           if (value.length != 0)
           {
               $("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
           }
       });
       $("#validation-errors").show();
   } else {
       $("#user-profile").attr('src',response.file);
   }
}
<img class="img-responsive profile-img margin-bottom-20"  alt="" id="user-profile">
  <input type="file" class="btn btn-sm btn-info" value="Edit Image" name="image" id="image">

UserController.php


    public function upload_image()
    {
        $file = Request::file('image');

        $file = $this->userRepo->updateAvatar($file,Auth::user()->user);
        
        return response()->json(['success' => true, 'file' => $file ]);
    }

DbUserRepository.php

public function updateAvatar($file,$user) { // Move the uploaded file to public/uploads/ folder

    $destinationPath = 'uploads/';

    $filename = $file->getClientOriginalName();
    
    $file->move($destinationPath, $filename);

    // save the file path on user avatar

    $user = User::where('id',$user->id)->first();

    $user->avatar = $destinationPath.$filename;

    $user->save();

    return asset($destinationPath.$filename);
}

jsartisan left a reply on Photo Upload Preview

You have to use ajax to preview the image.

jsartisan left a reply on Complicated Relationship

Yes. You should go with Polymorphic relations like jeffrey explained in this lesson - Polymorphic Huh ?

27 Aug
3 years ago

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@pmall I did the same thing but that was in php. But your code is really cool !! I will try it for sure :) Thanks a lot guys !

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@thomaskim @veve286 @willvincent

I have this . Although this code looks very dumb.But it is working :/


    public function getLabsHavingTests($tests)
    {
        $lab_ids = [];

        $lab_tests = LabTest::select('lab_id', DB::raw('count(*) as total'))
                        ->whereIn('test_id',$tests)
                        ->groupBy('lab_id')
                        ->get();

        foreach ($lab_tests as $lab_test) 
        {
            if(count($tests) == $lab_test->total)
            {
                $lab_ids[] = $lab_test->lab_id;
            }
        }


        $labs = Dc::whereIn('id',$lab_ids)->paginate(1);

        return $labs;
}

jsartisan left a reply on Complex Eloquent Relationship DB Selections

Not working. This gives empty array.

jsartisan left a reply on Complex Eloquent Relationship DB Selections

yes i have. test_id in lab_test is referencing to the id of test table.

lab_test.test_id --------> tests.id

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@thomaskim Not Working. 'id' column not found

jsartisan left a reply on Complex Eloquent Relationship DB Selections

i dont know how to upload the image here :P

jsartisan left a reply on Complex Eloquent Relationship DB Selections

id | test_id | price | lab_id | discount | is_home_collectable | created_at | updated_at

here are the columns for the pivot table.

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@thomaskim User is searching labs according to tests. So for e.g. "A blood test" can be available to multiple labs and a labs can have many tests. Thats why i needed a pivot table.

jsartisan left a reply on Complex Eloquent Relationship DB Selections

Error : "Column not found: 1054 Unknown column 'tests.lab_id' in"

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@veve286 i'm using a pivot table and that's why i used belongsToMany relationship.

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@willvincent

I'm not using the inverse relationship. So i didn't add that relationship. But since you asked, i added this in Test.php

public function dcs()
    {
      return $this->belongsToMany('App\Models\Dc');
    }

jsartisan left a reply on Complex Eloquent Relationship DB Selections

A Weird Error.

Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select count() as aggregate from labs where (select count() from tests inner join lab_test on tests.id = lab_test.test_id where lab_test.dc_id = labs.id and id = 1 and id = 3) >= 1)

jsartisan left a reply on Complex Eloquent Relationship DB Selections

This gives this error : "Call to undefined method Illuminate\Database\Query\Builder::test()"

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@veve286 that didn't work. it was showing error.

jsartisan left a reply on Complex Eloquent Relationship DB Selections

Test.php

class Test extends Model{

    protected $fillable = ['name', 'description'];


}

Lab.php

class Lab extends Model{

    protected $fillable = ['name', 'location_id', 'phone','description'];
    
    public function tests()
     {
            return $this->belongsToMany('App\Models\Test');
        }
}

jsartisan left a reply on Complex Eloquent Relationship DB Selections

@veve286 i have tried this. It returns empty array.

because its looks for something lke this "select * from lab_test where test_id = 1 and test_id = 3" which doesn't make any sense.