Retrieving data in Laravel using Eloquent and foreign keys












0















I am making a game library system for a project and trying to implement a search function which would display the user games that they are searching for.



I have two models called Game and GameInformation. This is due to many games having the same information, i.e. being the same game. The migration files look like:



GameInformation



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGameInformationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('game_information', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('genre');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Game_Information');
}
}


Game



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGamesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->integer('info_id')->unsigned();
$table->foreign('info_id')->references('id')->on('game_information');
$table->enum('type', ['disc', 'cartridge']);
$table->integer('platform_id')->unsigned();
$table->foreign('platform_id')->references('id')->on('platforms');
$table->integer('price');
$table->year('year_released');
$table->boolean('available')->default(true);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Games');
}
}


So what should happen once the user has called a search, it should retrieve the all the game informations that match their query, and then loop through them all and find the games that are associated with that information. In the end it should return an array of arrays where the inner arrays contain the game and the game information objects.



Search bar



<form class="form-inline" action="/search" method="POST" role="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search">
</div>
</form>


Search function in SearchController



public function search() {
$q = Input::get ( 'q' );
if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
return view ('home')->with('failureMsg','Nothing was found...');
}
$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
$games = array();
foreach($infos as $info) {
$gamesWithInfo = $info->games();
array_push($games, array($info, $gamesWithInfo));
}
if (count ( $games ) > 0)
return view ('home')->with( $games )->withQuery($q);
else
return view ('home')->with('failureMsg','Nothing was found...');
}


Display search results



<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
<div class="container">
<div class="row">
</div>
@if(!empty($failureMsg))
<div class="alert alert-failure"> {{ $failureMsg }}</div>
@endif
@if(isset($games))
HELLO
<p> The search results for your query <b> {{ $query }} </b> are :</p>
<h2>Games found:</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@foreach($games as $game)
<tr>
<td>{{$game(0)->title}}</td>
<td>{{$game(0)->description}}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
</div>
</div>
</div>


It doesn't display anything when a correct query is input, however it does display an error message when an incorrect one is input. So I'm thinking it's return an array of empty arrays.



Also in the SearchController on the line:



$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();


I have also tried making it:



$infos = GameInformation::where('title', 'like', '%' . $q .'%');


But that will return the error message where nothing is found.



Also the models:



Game



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class Game extends Eloquent
{
protected $primaryKey = 'id';

public function information() {
return $this->belongsTo('AppGameInformation');
}
}


GameInformation



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class GameInformation extends Eloquent
{
protected $table = 'game_information';
protected $primaryKey = 'id';

public function games() {
return $this->hasMany('AppGame', 'info_id');
}
}









share|improve this question























  • $info->games() uh, devin, have you ever heard ->with() for eager loading relations..? e.g. GameInformation::where('title', 'like', '%' . $q .'%')->get(); will be GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();. though i'm curious what error you get when you do GameInformation::where('title', 'like', '%' . $q .'%')->get();.

    – Bagus Tesa
    Nov 22 '18 at 1:01













  • I'm not getting any error, instead it just isn't displaying anything. I have tried the eager loading and I'm getting the same result. I show this in the post below I just made.

    – devinprogress
    Nov 22 '18 at 10:12
















0















I am making a game library system for a project and trying to implement a search function which would display the user games that they are searching for.



I have two models called Game and GameInformation. This is due to many games having the same information, i.e. being the same game. The migration files look like:



GameInformation



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGameInformationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('game_information', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('genre');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Game_Information');
}
}


Game



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGamesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->integer('info_id')->unsigned();
$table->foreign('info_id')->references('id')->on('game_information');
$table->enum('type', ['disc', 'cartridge']);
$table->integer('platform_id')->unsigned();
$table->foreign('platform_id')->references('id')->on('platforms');
$table->integer('price');
$table->year('year_released');
$table->boolean('available')->default(true);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Games');
}
}


So what should happen once the user has called a search, it should retrieve the all the game informations that match their query, and then loop through them all and find the games that are associated with that information. In the end it should return an array of arrays where the inner arrays contain the game and the game information objects.



Search bar



<form class="form-inline" action="/search" method="POST" role="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search">
</div>
</form>


Search function in SearchController



public function search() {
$q = Input::get ( 'q' );
if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
return view ('home')->with('failureMsg','Nothing was found...');
}
$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
$games = array();
foreach($infos as $info) {
$gamesWithInfo = $info->games();
array_push($games, array($info, $gamesWithInfo));
}
if (count ( $games ) > 0)
return view ('home')->with( $games )->withQuery($q);
else
return view ('home')->with('failureMsg','Nothing was found...');
}


Display search results



<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
<div class="container">
<div class="row">
</div>
@if(!empty($failureMsg))
<div class="alert alert-failure"> {{ $failureMsg }}</div>
@endif
@if(isset($games))
HELLO
<p> The search results for your query <b> {{ $query }} </b> are :</p>
<h2>Games found:</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@foreach($games as $game)
<tr>
<td>{{$game(0)->title}}</td>
<td>{{$game(0)->description}}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
</div>
</div>
</div>


It doesn't display anything when a correct query is input, however it does display an error message when an incorrect one is input. So I'm thinking it's return an array of empty arrays.



Also in the SearchController on the line:



$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();


I have also tried making it:



$infos = GameInformation::where('title', 'like', '%' . $q .'%');


But that will return the error message where nothing is found.



Also the models:



Game



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class Game extends Eloquent
{
protected $primaryKey = 'id';

public function information() {
return $this->belongsTo('AppGameInformation');
}
}


GameInformation



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class GameInformation extends Eloquent
{
protected $table = 'game_information';
protected $primaryKey = 'id';

public function games() {
return $this->hasMany('AppGame', 'info_id');
}
}









share|improve this question























  • $info->games() uh, devin, have you ever heard ->with() for eager loading relations..? e.g. GameInformation::where('title', 'like', '%' . $q .'%')->get(); will be GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();. though i'm curious what error you get when you do GameInformation::where('title', 'like', '%' . $q .'%')->get();.

    – Bagus Tesa
    Nov 22 '18 at 1:01













  • I'm not getting any error, instead it just isn't displaying anything. I have tried the eager loading and I'm getting the same result. I show this in the post below I just made.

    – devinprogress
    Nov 22 '18 at 10:12














0












0








0








I am making a game library system for a project and trying to implement a search function which would display the user games that they are searching for.



I have two models called Game and GameInformation. This is due to many games having the same information, i.e. being the same game. The migration files look like:



GameInformation



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGameInformationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('game_information', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('genre');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Game_Information');
}
}


Game



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGamesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->integer('info_id')->unsigned();
$table->foreign('info_id')->references('id')->on('game_information');
$table->enum('type', ['disc', 'cartridge']);
$table->integer('platform_id')->unsigned();
$table->foreign('platform_id')->references('id')->on('platforms');
$table->integer('price');
$table->year('year_released');
$table->boolean('available')->default(true);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Games');
}
}


So what should happen once the user has called a search, it should retrieve the all the game informations that match their query, and then loop through them all and find the games that are associated with that information. In the end it should return an array of arrays where the inner arrays contain the game and the game information objects.



Search bar



<form class="form-inline" action="/search" method="POST" role="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search">
</div>
</form>


Search function in SearchController



public function search() {
$q = Input::get ( 'q' );
if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
return view ('home')->with('failureMsg','Nothing was found...');
}
$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
$games = array();
foreach($infos as $info) {
$gamesWithInfo = $info->games();
array_push($games, array($info, $gamesWithInfo));
}
if (count ( $games ) > 0)
return view ('home')->with( $games )->withQuery($q);
else
return view ('home')->with('failureMsg','Nothing was found...');
}


Display search results



<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
<div class="container">
<div class="row">
</div>
@if(!empty($failureMsg))
<div class="alert alert-failure"> {{ $failureMsg }}</div>
@endif
@if(isset($games))
HELLO
<p> The search results for your query <b> {{ $query }} </b> are :</p>
<h2>Games found:</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@foreach($games as $game)
<tr>
<td>{{$game(0)->title}}</td>
<td>{{$game(0)->description}}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
</div>
</div>
</div>


It doesn't display anything when a correct query is input, however it does display an error message when an incorrect one is input. So I'm thinking it's return an array of empty arrays.



Also in the SearchController on the line:



$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();


I have also tried making it:



$infos = GameInformation::where('title', 'like', '%' . $q .'%');


But that will return the error message where nothing is found.



Also the models:



Game



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class Game extends Eloquent
{
protected $primaryKey = 'id';

public function information() {
return $this->belongsTo('AppGameInformation');
}
}


GameInformation



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class GameInformation extends Eloquent
{
protected $table = 'game_information';
protected $primaryKey = 'id';

public function games() {
return $this->hasMany('AppGame', 'info_id');
}
}









share|improve this question














I am making a game library system for a project and trying to implement a search function which would display the user games that they are searching for.



I have two models called Game and GameInformation. This is due to many games having the same information, i.e. being the same game. The migration files look like:



GameInformation



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGameInformationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('game_information', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('genre');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Game_Information');
}
}


Game



<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateGamesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->integer('info_id')->unsigned();
$table->foreign('info_id')->references('id')->on('game_information');
$table->enum('type', ['disc', 'cartridge']);
$table->integer('platform_id')->unsigned();
$table->foreign('platform_id')->references('id')->on('platforms');
$table->integer('price');
$table->year('year_released');
$table->boolean('available')->default(true);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('Games');
}
}


So what should happen once the user has called a search, it should retrieve the all the game informations that match their query, and then loop through them all and find the games that are associated with that information. In the end it should return an array of arrays where the inner arrays contain the game and the game information objects.



Search bar



<form class="form-inline" action="/search" method="POST" role="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search">
</div>
</form>


Search function in SearchController



public function search() {
$q = Input::get ( 'q' );
if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
return view ('home')->with('failureMsg','Nothing was found...');
}
$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
$games = array();
foreach($infos as $info) {
$gamesWithInfo = $info->games();
array_push($games, array($info, $gamesWithInfo));
}
if (count ( $games ) > 0)
return view ('home')->with( $games )->withQuery($q);
else
return view ('home')->with('failureMsg','Nothing was found...');
}


Display search results



<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
<div class="container">
<div class="row">
</div>
@if(!empty($failureMsg))
<div class="alert alert-failure"> {{ $failureMsg }}</div>
@endif
@if(isset($games))
HELLO
<p> The search results for your query <b> {{ $query }} </b> are :</p>
<h2>Games found:</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@foreach($games as $game)
<tr>
<td>{{$game(0)->title}}</td>
<td>{{$game(0)->description}}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
</div>
</div>
</div>


It doesn't display anything when a correct query is input, however it does display an error message when an incorrect one is input. So I'm thinking it's return an array of empty arrays.



Also in the SearchController on the line:



$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();


I have also tried making it:



$infos = GameInformation::where('title', 'like', '%' . $q .'%');


But that will return the error message where nothing is found.



Also the models:



Game



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class Game extends Eloquent
{
protected $primaryKey = 'id';

public function information() {
return $this->belongsTo('AppGameInformation');
}
}


GameInformation



<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use Eloquent;

class GameInformation extends Eloquent
{
protected $table = 'game_information';
protected $primaryKey = 'id';

public function games() {
return $this->hasMany('AppGame', 'info_id');
}
}






php laravel eloquent






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 0:58









devinprogressdevinprogress

184




184













  • $info->games() uh, devin, have you ever heard ->with() for eager loading relations..? e.g. GameInformation::where('title', 'like', '%' . $q .'%')->get(); will be GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();. though i'm curious what error you get when you do GameInformation::where('title', 'like', '%' . $q .'%')->get();.

    – Bagus Tesa
    Nov 22 '18 at 1:01













  • I'm not getting any error, instead it just isn't displaying anything. I have tried the eager loading and I'm getting the same result. I show this in the post below I just made.

    – devinprogress
    Nov 22 '18 at 10:12



















  • $info->games() uh, devin, have you ever heard ->with() for eager loading relations..? e.g. GameInformation::where('title', 'like', '%' . $q .'%')->get(); will be GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();. though i'm curious what error you get when you do GameInformation::where('title', 'like', '%' . $q .'%')->get();.

    – Bagus Tesa
    Nov 22 '18 at 1:01













  • I'm not getting any error, instead it just isn't displaying anything. I have tried the eager loading and I'm getting the same result. I show this in the post below I just made.

    – devinprogress
    Nov 22 '18 at 10:12

















$info->games() uh, devin, have you ever heard ->with() for eager loading relations..? e.g. GameInformation::where('title', 'like', '%' . $q .'%')->get(); will be GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();. though i'm curious what error you get when you do GameInformation::where('title', 'like', '%' . $q .'%')->get();.

– Bagus Tesa
Nov 22 '18 at 1:01







$info->games() uh, devin, have you ever heard ->with() for eager loading relations..? e.g. GameInformation::where('title', 'like', '%' . $q .'%')->get(); will be GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();. though i'm curious what error you get when you do GameInformation::where('title', 'like', '%' . $q .'%')->get();.

– Bagus Tesa
Nov 22 '18 at 1:01















I'm not getting any error, instead it just isn't displaying anything. I have tried the eager loading and I'm getting the same result. I show this in the post below I just made.

– devinprogress
Nov 22 '18 at 10:12





I'm not getting any error, instead it just isn't displaying anything. I have tried the eager loading and I'm getting the same result. I show this in the post below I just made.

– devinprogress
Nov 22 '18 at 10:12












3 Answers
3






active

oldest

votes


















0














To start, verify the value of $q is what you are expecting to make sure the first condition isn't getting tripped:



$q = Input::get ( 'q' );
dd($q); // temporarily to verify the value
if(strlen($q) == 0 || strpos($q, '%') !== false) {
return view ('home')->with('failureMsg','Nothing was found...');
}


Then verify that you are getting the correct results from your query:



$infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
dd($infos); // temporarily to verify at least one item is found


If you are going through your foreach($infos as $info) loop at least once, then there should be at least one item in your $games array. If $games is empty, then you will hit your the second error condition.



Another issue:



$gamesWithInfo = $info->games();


You need to actually fetch the games. With your current code you could do it like this:



$gamesWithInfo = $info->games()->get();


Or just:



$gamesWithInfo = $info->games;


But it would be better to eager load them:



$infos = GameInformation::with('games')
->where('title', 'like', '%' . $q .'%')->get();


Then use:



$gamesWithInfo = $info->games;


Inside your loop.






share|improve this answer

































    0














    So I have changed my search function to this:



    public function search() {
    $q = Input::get ( 'q' );
    if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
    return view ('home')->with('failureMsg','Nothing was found...');
    }
    $infos = GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();
    $games = array();
    foreach($infos as $info) {
    $gamesWithInfo = $info->games;
    array_push($games, array($info, $gamesWithInfo));
    }
    if (count ( $games ) > 0)
    return view ('home')->with( $games )->withQuery($q);
    else
    return view ('home')->with('failureMsg','Nothing was found...');
    }


    But I'm getting no output as before. I also did the dd() and the input was correct and infos array was not empty.



    The output on the site looks like this when nothing is found:



    enter image description here



    But it's returning this when something is found:
    enter image description here






    share|improve this answer































      0














      I have seemed to fix the problem, it seems as $games was not being recognised so when I was returning the view I changed it to:



      return view ('home')->with('gamesAndInfo', $gamesWithInfo )->withQuery($q);


      And now it is being set properly.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422507%2fretrieving-data-in-laravel-using-eloquent-and-foreign-keys%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        To start, verify the value of $q is what you are expecting to make sure the first condition isn't getting tripped:



        $q = Input::get ( 'q' );
        dd($q); // temporarily to verify the value
        if(strlen($q) == 0 || strpos($q, '%') !== false) {
        return view ('home')->with('failureMsg','Nothing was found...');
        }


        Then verify that you are getting the correct results from your query:



        $infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
        dd($infos); // temporarily to verify at least one item is found


        If you are going through your foreach($infos as $info) loop at least once, then there should be at least one item in your $games array. If $games is empty, then you will hit your the second error condition.



        Another issue:



        $gamesWithInfo = $info->games();


        You need to actually fetch the games. With your current code you could do it like this:



        $gamesWithInfo = $info->games()->get();


        Or just:



        $gamesWithInfo = $info->games;


        But it would be better to eager load them:



        $infos = GameInformation::with('games')
        ->where('title', 'like', '%' . $q .'%')->get();


        Then use:



        $gamesWithInfo = $info->games;


        Inside your loop.






        share|improve this answer






























          0














          To start, verify the value of $q is what you are expecting to make sure the first condition isn't getting tripped:



          $q = Input::get ( 'q' );
          dd($q); // temporarily to verify the value
          if(strlen($q) == 0 || strpos($q, '%') !== false) {
          return view ('home')->with('failureMsg','Nothing was found...');
          }


          Then verify that you are getting the correct results from your query:



          $infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
          dd($infos); // temporarily to verify at least one item is found


          If you are going through your foreach($infos as $info) loop at least once, then there should be at least one item in your $games array. If $games is empty, then you will hit your the second error condition.



          Another issue:



          $gamesWithInfo = $info->games();


          You need to actually fetch the games. With your current code you could do it like this:



          $gamesWithInfo = $info->games()->get();


          Or just:



          $gamesWithInfo = $info->games;


          But it would be better to eager load them:



          $infos = GameInformation::with('games')
          ->where('title', 'like', '%' . $q .'%')->get();


          Then use:



          $gamesWithInfo = $info->games;


          Inside your loop.






          share|improve this answer




























            0












            0








            0







            To start, verify the value of $q is what you are expecting to make sure the first condition isn't getting tripped:



            $q = Input::get ( 'q' );
            dd($q); // temporarily to verify the value
            if(strlen($q) == 0 || strpos($q, '%') !== false) {
            return view ('home')->with('failureMsg','Nothing was found...');
            }


            Then verify that you are getting the correct results from your query:



            $infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
            dd($infos); // temporarily to verify at least one item is found


            If you are going through your foreach($infos as $info) loop at least once, then there should be at least one item in your $games array. If $games is empty, then you will hit your the second error condition.



            Another issue:



            $gamesWithInfo = $info->games();


            You need to actually fetch the games. With your current code you could do it like this:



            $gamesWithInfo = $info->games()->get();


            Or just:



            $gamesWithInfo = $info->games;


            But it would be better to eager load them:



            $infos = GameInformation::with('games')
            ->where('title', 'like', '%' . $q .'%')->get();


            Then use:



            $gamesWithInfo = $info->games;


            Inside your loop.






            share|improve this answer















            To start, verify the value of $q is what you are expecting to make sure the first condition isn't getting tripped:



            $q = Input::get ( 'q' );
            dd($q); // temporarily to verify the value
            if(strlen($q) == 0 || strpos($q, '%') !== false) {
            return view ('home')->with('failureMsg','Nothing was found...');
            }


            Then verify that you are getting the correct results from your query:



            $infos = GameInformation::where('title', 'like', '%' . $q .'%')->get();
            dd($infos); // temporarily to verify at least one item is found


            If you are going through your foreach($infos as $info) loop at least once, then there should be at least one item in your $games array. If $games is empty, then you will hit your the second error condition.



            Another issue:



            $gamesWithInfo = $info->games();


            You need to actually fetch the games. With your current code you could do it like this:



            $gamesWithInfo = $info->games()->get();


            Or just:



            $gamesWithInfo = $info->games;


            But it would be better to eager load them:



            $infos = GameInformation::with('games')
            ->where('title', 'like', '%' . $q .'%')->get();


            Then use:



            $gamesWithInfo = $info->games;


            Inside your loop.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 '18 at 1:46

























            answered Nov 22 '18 at 1:25









            PeterPeter

            8841213




            8841213

























                0














                So I have changed my search function to this:



                public function search() {
                $q = Input::get ( 'q' );
                if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
                return view ('home')->with('failureMsg','Nothing was found...');
                }
                $infos = GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();
                $games = array();
                foreach($infos as $info) {
                $gamesWithInfo = $info->games;
                array_push($games, array($info, $gamesWithInfo));
                }
                if (count ( $games ) > 0)
                return view ('home')->with( $games )->withQuery($q);
                else
                return view ('home')->with('failureMsg','Nothing was found...');
                }


                But I'm getting no output as before. I also did the dd() and the input was correct and infos array was not empty.



                The output on the site looks like this when nothing is found:



                enter image description here



                But it's returning this when something is found:
                enter image description here






                share|improve this answer




























                  0














                  So I have changed my search function to this:



                  public function search() {
                  $q = Input::get ( 'q' );
                  if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
                  return view ('home')->with('failureMsg','Nothing was found...');
                  }
                  $infos = GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();
                  $games = array();
                  foreach($infos as $info) {
                  $gamesWithInfo = $info->games;
                  array_push($games, array($info, $gamesWithInfo));
                  }
                  if (count ( $games ) > 0)
                  return view ('home')->with( $games )->withQuery($q);
                  else
                  return view ('home')->with('failureMsg','Nothing was found...');
                  }


                  But I'm getting no output as before. I also did the dd() and the input was correct and infos array was not empty.



                  The output on the site looks like this when nothing is found:



                  enter image description here



                  But it's returning this when something is found:
                  enter image description here






                  share|improve this answer


























                    0












                    0








                    0







                    So I have changed my search function to this:



                    public function search() {
                    $q = Input::get ( 'q' );
                    if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
                    return view ('home')->with('failureMsg','Nothing was found...');
                    }
                    $infos = GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();
                    $games = array();
                    foreach($infos as $info) {
                    $gamesWithInfo = $info->games;
                    array_push($games, array($info, $gamesWithInfo));
                    }
                    if (count ( $games ) > 0)
                    return view ('home')->with( $games )->withQuery($q);
                    else
                    return view ('home')->with('failureMsg','Nothing was found...');
                    }


                    But I'm getting no output as before. I also did the dd() and the input was correct and infos array was not empty.



                    The output on the site looks like this when nothing is found:



                    enter image description here



                    But it's returning this when something is found:
                    enter image description here






                    share|improve this answer













                    So I have changed my search function to this:



                    public function search() {
                    $q = Input::get ( 'q' );
                    if(strlen($q) == 0 || strpos($q, '%') !== false) { // For security
                    return view ('home')->with('failureMsg','Nothing was found...');
                    }
                    $infos = GameInformation::with('games')->where('title', 'like', '%' . $q .'%')->get();
                    $games = array();
                    foreach($infos as $info) {
                    $gamesWithInfo = $info->games;
                    array_push($games, array($info, $gamesWithInfo));
                    }
                    if (count ( $games ) > 0)
                    return view ('home')->with( $games )->withQuery($q);
                    else
                    return view ('home')->with('failureMsg','Nothing was found...');
                    }


                    But I'm getting no output as before. I also did the dd() and the input was correct and infos array was not empty.



                    The output on the site looks like this when nothing is found:



                    enter image description here



                    But it's returning this when something is found:
                    enter image description here







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 22 '18 at 10:11









                    devinprogressdevinprogress

                    184




                    184























                        0














                        I have seemed to fix the problem, it seems as $games was not being recognised so when I was returning the view I changed it to:



                        return view ('home')->with('gamesAndInfo', $gamesWithInfo )->withQuery($q);


                        And now it is being set properly.






                        share|improve this answer




























                          0














                          I have seemed to fix the problem, it seems as $games was not being recognised so when I was returning the view I changed it to:



                          return view ('home')->with('gamesAndInfo', $gamesWithInfo )->withQuery($q);


                          And now it is being set properly.






                          share|improve this answer


























                            0












                            0








                            0







                            I have seemed to fix the problem, it seems as $games was not being recognised so when I was returning the view I changed it to:



                            return view ('home')->with('gamesAndInfo', $gamesWithInfo )->withQuery($q);


                            And now it is being set properly.






                            share|improve this answer













                            I have seemed to fix the problem, it seems as $games was not being recognised so when I was returning the view I changed it to:



                            return view ('home')->with('gamesAndInfo', $gamesWithInfo )->withQuery($q);


                            And now it is being set properly.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 22 '18 at 10:32









                            devinprogressdevinprogress

                            184




                            184






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422507%2fretrieving-data-in-laravel-using-eloquent-and-foreign-keys%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                Alcedinidae

                                RAC Tourist Trophy