AlenV

Experience

3,760

0 Best Reply Awards

  • Member Since 3 Months Ago
  • 32 Lessons Completed
  • 3 Favorites

21st March, 2018

AlenV left a reply on Optional 'with' • 2 months ago

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

AlenV started a new conversation Optional 'with' • 2 months ago

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 • 2 months ago

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 • 2 months ago

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

AlenV started a new conversation Column Not Found • 2 months ago

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'));

13th March, 2018

AlenV started a new conversation Use Relationship Where In Scope • 2 months ago

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 )

12th March, 2018

AlenV started a new conversation Make One Query To Go Through All Tables • 2 months ago

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');
    }

11th March, 2018

AlenV left a reply on Access Array Values With Only() • 2 months ago

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() • 2 months ago

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();
        });

10th March, 2018

AlenV left a reply on Access Pivot Table Values • 2 months ago

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 • 2 months ago

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.

27th February, 2018

AlenV left a reply on Laravel HasMany Relationship • 2 months ago

@skliche it works, thank you!

AlenV started a new conversation Laravel HasMany Relationship • 2 months ago

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.

14th February, 2018

AlenV left a reply on Laravel 5.5 Ajax Problem • 3 months ago

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 • 3 months ago

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 • 3 months ago

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);
        }
    });
}

13th February, 2018

AlenV left a reply on Laravel 5.5 Ajax Problem • 3 months ago

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

AlenV left a reply on Laravel 5.5 Ajax Problem • 3 months ago

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 • 3 months ago

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

AlenV started a new conversation Laravel 5.5 Ajax Problem • 3 months ago

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);
        }
    });

}
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.