AlenV

AlenV

Member Since 8 Months Ago

Experience Points 3,880
Experience
Level
Lessons Completed 32
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

17 Sep
1 month ago

AlenV started a new conversation Execute Php Script With Axios

Is there a way to execute php script with axios? This is what I am trying and it gives me back all the code back in response instead of executing.

    axios.get('http://localhost:8080/script.php', {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Allow-Control-Allow-Origin': '*'
                },
                params: {
                    'id': 1
                }
            })
            .then((response) => (
                console.log(response)
            ))
            .catch((error) => (
                console.log(error)
            ))
04 Sep
2 months ago

AlenV left a reply on Get Laravel Session With Vue

I have Main Layout for an application which is called HomeComponent.vue

<template>
  <v-app id="inspire" dark>

    <v-navigation-drawer
      v-model="drawer"
      clipped
      fixed
      app
    >
      <v-list dense>
        <v-list-tile>
          <v-list-tile-action>
            <v-icon>mdi-login</v-icon>
          </v-list-tile-action>
          <v-list-tile-content>
            <router-link to="/login">
                <v-list-tile-title>Login</v-list-tile-title>
            </router-link>
          </v-list-tile-content>
        </v-list-tile>
        <v-list-tile>
          <v-list-tile-action>
            <v-icon>mdi-account-plus</v-icon>
          </v-list-tile-action>
          <v-list-tile-content>
              <router-link to="/register">
                <v-list-tile-title>Register</v-list-tile-title>
              </router-link>
          </v-list-tile-content>
        </v-list-tile>
      </v-list>
    </v-navigation-drawer>

    <v-toolbar app fixed clipped-left>
      <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon>
      <v-toolbar-title>Logo</v-toolbar-title>
    </v-toolbar>

    <v-container fill-height>
        <v-layout justify-center align-center>
            <router-view></router-view>
        </v-layout>
    </v-container>

    <v-footer app fixed class="justify-content-center">
      <span>Logo &copy; 2018.</span>
    </v-footer>

  </v-app>
</template>

<script>
  export default {
    mounted() {
        console.log('Component mounted.')
    },
    data: () => ({
      drawer: true
    }),
    props: {
      source: String
    }
  }
</script>

In that layout I use router to change between Login and Register components. This is the LoginComponent.vue

<template>
    <v-content>
        <v-container fluid fill-height>
            <v-layout align-center justify-center>
                <v-flex xs12 sm8 md6>
                    <v-alert
                    v-model="successAlert"
                    type="success"
                    >
                    This is a success alert.
                    </v-alert>
                    <v-card class="elevation-12">
                        <v-toolbar dark color="primary">
                            <v-toolbar-title>Login</v-toolbar-title>
                        </v-toolbar>
                        <v-card-text>
                            <v-form>
                                <v-text-field
                                prepend-icon="person"
                                v-model="username"
                                :rules="usernameRules"
                                label="Username"
                                type="text"></v-text-field>

                                <v-text-field
                                prepend-icon="lock"
                                v-model="password"
                                :rules="passwordRules"
                                label="Password"
                                type="password"></v-text-field>
                            </v-form>
                        </v-card-text>
                        <v-card-actions>

                                <router-link to="/forgot-password">
                                    <a style="color: white;">Forgot your password?</a>
                                </router-link>

                            <v-spacer></v-spacer>
                            <v-btn color="primary">Login</v-btn>
                        </v-card-actions>
                    </v-card>
                </v-flex>
            </v-layout>
      </v-container>
    </v-content>
</template>

<script>
  export default {
    mounted: function () {
        this.$session.start();
        if (this.$session.exists('verified')){
            console.log('Yes it exists');
            this.$session.destroy();
            this.showSuccessAlert();
        }
    },
    data: () => ({
      drawer: null,
      successAlert: 0,
      username: '',
      usernameRules: [
          v => !!v || 'Username is required'
      ],
      password: '',
      passwordRules: [
          v => !!v || 'Password is required'
      ]
    }),
    props: {
      source: String,
    },
    methods: {
        showSuccessAlert() {
            this.successAlert = 1;
        }
    }
  }
</script>

In this Login Component I have alert which should be shown when there is 'verified' session which comes from UserController

This is the function from UserController

public function activateAccount($email, $token) {
        $user = User::where('email', $email)->firstOrFail();

        if($user->confirmation_token === $token) {
            $user->mail_confirmed = 1;
            $user->save();
            return redirect('/login')->with('verified', 'Account successfully verified. You can log in now.');
        }
    }

And I have route in web.php for all of that.

Route::get('/activate/{email}/{token}', '[email protected]');
03 Sep
2 months ago

AlenV left a reply on Get Laravel Session With Vue

@bobbybouwmann okay, thank you. I'm new to Vue so I don't really know how it goes.

AlenV started a new conversation Get Laravel Session With Vue

Hello,

I have redirect in UserController with flashed session data.

    return redirect('/login')->with('verified', 'Account successfully verified. You can log in now.');

And how would I access it now in Vue Component? I tried with vue-session but it doesn't work.

21 Mar
7 months ago

AlenV left a reply on Optional 'with'

Oh.. yes. Thank you, it is working now.

AlenV started a new conversation Optional 'with'

How would something like this be possible? I need that 'with()' to be optional.

public function scopeCategoryLang($query, $category, $categoryBool){
        return $query->whereHas('categories', function ($query) use ($category) {
            if($category === 'null'){
                $query = $query->whereNull('category_id');
            }else if($category === '!null'){
                $query = $query->whereNotNull('category_id');
            }else if($category >= 0){
                $query = $query->where('category_id', '=', $category);
            }
        });
        
        if($categoryBool==1){
            return $query->with(['meals.categories', 'categories']);
        }else{
            return $query;
        }
            
    }

AlenV left a reply on Column Not Found

So I do that like this?

public function scopeCategoryLang($query, $category){
        return $query->whereHas('categories', function ($query) use ($category) {
            if($category === 'null'){
                $query = $query->whereNull('category_id');
            }else if($category === '!null'){
                $query = $query->whereNotNull('category_id');
            }else if($category >= 0){
                $query = $query->where('category_id', '=', $category);
            }
        });
        
        $query = $query->with(['meals.categories', 'categories']);
        return $query;
            
    }

AlenV left a reply on Column Not Found

I have pivot table that contains 'category_id', 'lang_id' and 'title'

AlenV started a new conversation Column Not Found

I get an error 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_id' in 'where clause' (SQL: select * from langs where category_id = 1 and code = en)' when I run that query functions inside Lang model.

Lang model

class Lang extends Model
{
public function meals(){
        return $this->belongsToMany('App\Meal')->withPivot('title', 'description');
    }

    public function categories(){
        return $this->belongsToMany('App\Category')->withPivot('title');
    }

public function scopeCategoryLang($query, $category){
        
        if($category === 'null'){
            $query = $query->whereNull('category_id');
        }else if($category === '!null'){
            $query = $query->whereNotNull('category_id');
        }else if($category >= 0){
            $query = $query->where('category_id', '=', $category);
        }
        
        return $query->with(['meals.categories', 'categories']);
            
    }

}

Meal model

class Meal extends Model
{   
public function langs(){
        return $this->belongsToMany('App\Lang')->withPivot('title', 'description');
    }

    public function categories(){
        return $this->belongsTo('App\Category', 'category_id');
    }
}

Category model

class Category extends Model
{
    public function langs(){
        return $this->belongsToMany('App\Lang')->withPivot('title');
    }

    public function meals(){
        return $this->hasMany('App\Meal');
    }
}

Controller

$language = $request->input('lang');
$category = $request->input('category');

$meal = $lang->mealLang()
        ->categoryLang($category)
        ->tagLang()
        ->ingredientLang()
        ->where('code', $language)
        ->get();

        $meal = json_decode($meal, true);
        
        return view('meal', compact('meal'));
13 Mar
8 months ago

AlenV started a new conversation Use Relationship Where In Scope

Is there a way I could implement this relationship's where

public function langs($lang){
        return $this->belongsToMany('App\Lang')->withPivot('title', 'description')->where('code', $lang);
}

in this scope?

public function scopeGetMealLanguage($query){
        return $query->whereHas('langs', function ($query){
           return $query->where('code', 'hr');
        })->with('langs');
}

This is what I get when I remove ->where() from langs relationship and that's not what I need to get. I need only one language to be shown. ( https://imgur.com/a/uEjHu )

This is with ->where() in langs relationship included and that's what I want to get. ( https://imgur.com/a/tjJzf )

12 Mar
8 months ago

AlenV started a new conversation Make One Query To Go Through All Tables

Is there a way I could connect this two queries? I need to get category under every meal.

public function scopeMyMeals($query, $language){
        $mealPivot = $this->meals()->getTable();
        $categoryPivot = $this->categories()->getTable();

        $query = $query->whereHas('meals', function($q) use ($language, $mealPivot) {
            $q->where('code', $language);
        });

        $query = $query->whereHas('categories', function($q) use ($language, $categoryPivot) {
            $q->where('code', $language);
        });
        

        return $query->with('meals', 'categories');
    }
11 Mar
8 months ago

AlenV left a reply on Access Array Values With Only()

It works but I get double https://imgur.com/jEHlcWb

$meals = Meal::with(['langs' => function ($query) {
            $query->select('title', 'description');
        }])->get();

$meal = $meals->toArray();
dd($meal);

AlenV started a new conversation Access Array Values With Only()

Hello, how do I get values of 'title' and 'description' from here https://imgur.com/4eaEx1a ?

$meals = Meal::with('langs')->get();

$subset = $meals->map(function ($meal){
            return collect($meal->toArray())
            ->only(['langs'])
            ->all();
        });
10 Mar
8 months ago

AlenV left a reply on Access Pivot Table Values

With raw sql it will be something like this

SELECT * FROM meals a
LEFT JOIN lang_meal b ON b.meal_id=a.id
LEFT JOIN langs c ON b.lang_id=c.id
WHERE code='en';

AlenV started a new conversation Access Pivot Table Values

Hello,

I'm trying to create multilanguage website. But I can't access values from pivot tables.

Meal model

class Meal extends Model
{
    public function langs(){
        return $this->belongsToMany('App\Lang');
    }
}

Langs Model

class Meal extends Model
{
    public function langs(){
        return $this->belongsToMany('App\Lang');
    }
}

Meal Controller

class MealController extends Controller
{
    public function listMeals(Meal $meal){
        $meal = Meal::all()->langs()->get();
        return view('meal', compact('meal'));
    }
}

Create langs table

public function up()
    {
        Schema::create('langs', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('code');
            $table->timestamps();
        });
    }

Create meals table

public function up()
    {
        Schema::create('meals', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->nullable($value = true);
            $table->string('status');
            $table->timestamps();
        });

        Schema::create('lang_meal', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('meal_id');
            $table->integer('lang_id');
            $table->string('title');
            $table->string('description');
            $table->timestamps();
        });
    }

I want to access that 'Title' and 'Description' from 'lang_meal' table.

27 Feb
8 months ago

AlenV left a reply on Laravel HasMany Relationship

@skliche it works, thank you!

AlenV started a new conversation Laravel HasMany Relationship

Hello,

How do I return values from both Meal and Category?

Meal Model

    protected $primaryKey = 'meal_id';

    public function category(){
        return $this->belongsTo('App\Category', 'category_id');
    }

Category Model

    protected $primaryKey = 'category_id';

    public function meal() {
        return $this->hasMany('App\Meal', 'category_id', 'category_id');
    }


Controller

public function mealCategory() {
        $meals = Meal::all();
        return view('meals', compact('meals'));
    }

Meal DB

Schema::create('meals', function (Blueprint $table) {
            $table->increments('meal_id');
            $table->string('meal_name');
            $table->string('meal_description');
            $table->string('meal_status');
            $table->integer('category_id')->nullable($value = true);
            $table->timestamps();
        });

Category DB

Schema::create('categories', function (Blueprint $table) {
            $table->increments('category_id');
            $table->string('category_title');
            $table->string('category_slug');
            $table->timestamps();
        });

In View I have only {{$meals}} and it gives me values only from Meal table and I want to get values from both tables.

14 Feb
8 months ago

AlenV left a reply on Laravel 5.5 Ajax Problem

It works, thank you for helping and teaching me, much appreciated. Now I have to make it work with paginator, but won't bother you anymore. Thank you once again.

AlenV left a reply on Laravel 5.5 Ajax Problem

I did as you said, and now it returns only that 'carfeature_data' file. So I think the problem is here in controller.

$view = view('private.carfeature.carfeature_data', compact('carFeatures', 'sortBy'));

Should I create new function in controller which will be called by ajax?

AlenV left a reply on Laravel 5.5 Ajax Problem

Okay, I've done that, and now it changes but I get like duplicate page.

HTML

@extends('layouts.main')

@section('title')
Car feature
@endsection

@section('content')

<?php $number=1;?>

<!-- Page title and Order by -->
<div class="row mt-5">

    <!-- Page title -->
    <div class="col-md-6 d-flex justify-content-left">
        <h1 class="text-left">Car feature</h1>
    </div>

    <!-- Sort By -->
    <div class="col-md-6 d-flex justify-content-right">

        <div class="col-md-5 mt-3">
            <h4 class="text-center">Sort by</h4>
        </div>

        <div class="col-md-7 mt-3">
            <select id="carFeatureSort" class="form-control" onchange="sortCarFeatures()">
                <option value="az">
                    Name A-Z
                </option>
                <option value="za">
                    Name Z-A
                </option>
            </select>
        </div>
    </div>
</div>

<div class="row justify-content-center mt-5">
    <div class="col-md-12">
        <table class="table table-striped table-inverse carfeature_table">
            <thead>
                <tr>
                    <th class="text-center">
                        #
                    </th>
                    <th class="text-center">
                        Feature name
                    </th>
                    @if(Auth::user()->user_rights==='Admin')
                    <th class="text-center">
                        Option
                    </th>
                    @endif
                </tr>
            </thead>

            <tbody>
                @foreach($carFeatures as $carFeature)
                <tr>
                    <td class="text-center">
                        {{$number}}<?php $number++;?>
                    </td>
                    <td class="text-center">
                        {{$carFeature->car_feature_name}}
                    </td>
                    @if(Auth::user()->user_rights==='Admin')
                    <td class="text-center">
                        <a href="/carfeature_edit/{{$carFeature->car_feature_id}}">Edit</a> | <a href="/carfeature_remove/{{$carFeature->car_feature_id}}">Remove</a>
                    </td>
                    @endif
                </tr>

                @endforeach

                @if(Auth::user()->user_rights==='Admin')
                <tr>
                    <td class="text-center" colspan="3">
                        <a href="/carfeature_add">Add new feature</a>
                    </td>
                </tr>
                @endif

            </tbody>
        </table>


        <!-- Paginator-->
        <div class="row mt-5 justify-content-center">
            <?php
            $number = $number;
            echo $carFeatures->render();
            ?>
        </div>

    </div>
</div>

<p id="sorttest">{{$sortBy}}</p>

@endsection

Controller

// Function to fetch all car features for listing
    public function listCarFeatures(Request $request) {
        $sortBy = 'az';
        if($request->has('sortBy')){
            $sortBy = $request->input('sortBy');
        }

        if($sortBy == 'az') {
            // Get car features from Database
            $carFeatures = DB::table('car_features')->orderBy('car_feature_name', 'asc')->paginate(5);
        } else {
            $carFeatures = DB::table('car_features')->orderBy('car_feature_name', 'desc')->paginate(5);
        }

        $view = view('private.carfeature.carfeature_show', compact('carFeatures', 'sortBy'));
        return $view->render();
    }

AJAX

function sortCarFeatures() {
    x = document.getElementById('carFeatureSort').value;

    $.ajax({
        url: '/carfeature',
        type: 'GET',
        data: { sortBy: x },
        success: function (response) {
            $('div.carfeature_table').replaceWith(response);
        },
        error: function(response){
            console.log('Error: ' + response);
        }
    });
}
13 Feb
9 months ago

AlenV left a reply on Laravel 5.5 Ajax Problem

Alright. Yes, I want it to change the existing HTML.

AlenV left a reply on Laravel 5.5 Ajax Problem

Hmm now when I put order by Z-A it gives me response what it should, but it doesn't update the view

AlenV left a reply on Laravel 5.5 Ajax Problem

Oh my bad, forgot to delete it. I removed it, but still not working

AlenV started a new conversation Laravel 5.5 Ajax Problem

Hello,

The problem is that I want to sort CarFeatures by name, but when I change listing from A-Z to Z-A nothing happens, I see the request in developer tools, but no changes.

Route

    Route::get('/carfeature/{sortBy}', ['uses' => '[email protected]']);

CarFeatureController

public function listCarFeatures(Request $request, $sortBy) {
        if($request->has('sortBy')){
            $sortBy = $request->input('sortBy');

        }
        if($sortBy == 'az') {
            // Get car features from Database
            $carFeatures = DB::table('car_features')->orderBy('car_feature_name', 'asc')->paginate(5);
        } else {
            $carFeatures = DB::table('car_features')->orderBy('car_feature_name', 'desc')->paginate(5);
        }

        $carFeatures = DB::table('car_features')->orderBy('car_feature_name', 'asc')->paginate(5);

        // Return view with CarFeatures
        return view('private.carfeature.carfeature_show')
        ->with(['carFeatures' => $carFeatures]);
    }

AJAX

function sortCarFeatures() {
    x = document.getElementById('carFeatureSort').value;

    $.ajax({
        url: 'carfeature',
        type: 'GET',
        data: { sortBy: x },
        success: function(response){
            console.log('Success: ' + response);
        },
        error: function(response){
            console.log('Error: ' + response);
        }
    });

}