I've been following the Laracasts Project-Flyer and have come to an end of the current videos in the series. I have decided to go off and expand on the app myself.
I'm trying to display the latest 3 flyers ( or in my case, classifieds) on the home page, along with an image.
I have been able to pull the last 3 entries and display them fine on the home page, but I've been trying to follow the same approach of displaying the images on the classified page, for the images for each classified on the home page.
Here is my code I have used.
Classified Model snippet:
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class classified extends Model
{
...
public function photos()
{
return $this->hasMany('App\classified_photo');
}
...
public static function getLatestClassifeds()
{
return DB::table('classifieds')
->select('ad_title','description')
->orderBy('created_at','desc')
->take(3)
->get();
}
...
Home Page Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\classifiedRequest;
use App\Http\Controllers\Controller;
use App\classified;
use App\classified_photo;
class HomeController extends Controller
{
public function show()
{
$classifieds = classified::getLatestClassifeds();
return view('pages.home', compact('classifieds'));
}
}
Home View:
#foreach($classifieds as $classified)
<div class="col-xs-6 col-sm-4">
<div class="col-xs-12">
#if($classified->photos)
#foreach($classified->photos as $photo)
<img src="/{{$photo->thumbnail_path}}" class="img-responsive">
#endforeach
#endif
</div>
<div class="col-xs-12">
<div class="classified-desc">
<h2>{{$classified->ad_title}}</h2>
<p>{{$classified->description}}</p>
</div>
</div>
<div class="col-xs-12">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Left</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Right</button>
</div>
</div>
</div>
</div>
#endforeach
This code returns this error when I try to view the home page:
Undefined property: stdClass::$photos (View: /var/www/html/barrys-bikes.dev/resources/views/pages/home.blade.php)
As I say, displaying the 3 classifieds works fine, its just this issue with trying to then pull an image for each one.
The problems is, because you using DB::table()... instead of Eloquent ORM. Do something like this:
public static function getLatestClassifeds()
{
return self::orderBy('created_at','desc')
->take(3)->get(['ad_title', 'description']);
}
Related
im new at Laravel, so i have following problem:
I have db with issue table, that contains 15 names of diseases with it's description. This is my model
class Issue extends Model
{
use HasFactory;
use SoftDeletes;
protected $guarded = false;
public function gender() {
return $this->belongsTo(BodyPart::class);
}
}
And here's controller:
use App\Http\Controllers\Controller;
use App\Models\Issue;
class IndexController extends Controller
{
public function __invoke()
{
$eye_issues = Issue::all();
return view('app.issues.man.eyes.index', compact('eye_issues'));
}
}
And finally below my blade file:
<main>
<section id="schedule" class="section-with-bg">
<ul class="nav nav-tabs" role="tablist" data-aos="fade-up" data-aos-delay="100">
#foreach($eye_issues as $issue)
#if($issue->body_part_id == 2 and $issue->gender_id == 1)
<li class="nav-item">
<a class="nav-link" href="#issue-{{ $issue->id }}" role="tab"
data-bs-toggle="tab">{{ $issue->issue }}</a>
</li>
#endif
#endforeach
</ul>
<div class="tab-content row justify-content-center" data-aos="fade-up" data-aos-delay="200">
#foreach($eye_issues as $issue)
#if($issue->body_part_id == 2 and $issue->gender_id == 1)
<div role="tabpanel" class="col-lg-9 tab-pane fade show active" id="issue-{{ $issue->id }}">
<div class="row schedule-item justify-content-center">
<div class="col-md-10" style=text-align:center>
<h4>{{ $issue->description }}</h4>
Test yourself
</div>
</div>
</div>
#endif
#endforeach
</div>
</div>
</section>
</main>
So problem is, after loading the page, navigation tabs should show all disease names (as it does) and the description section must be empty and show according description of disease that selected from nav-tabs and change description if disease is changed from nav-tabs. But after loading page, in the description section, there are all disease description, even nav-tabs selected to none onload. Only after selecting all diseases from nav-tabs, page works properly.
P.S I use MySQL if case u wanted to know. i tried to use all JS and CSS hide and show functions and other methods from internet, but no one works, and i guess it depends only on laravel it self. if you dont understand what i mean, comment it, i'll leave link for demo video of the issue
Hi I think I'm misunderstanding casts? Basically I am trying to display an already stored array back to my view and its not working, i have already stored the arrays and im just trying to retrieve them into plain text
I have a table:
> Games
>>id |
>>name |
>>mode
MyController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\Game;
use App\Mode;
class MyController extends Controller
{
public function gameView($id)
{
$game = Game::find($id);
return view('admin.game.view', ['game' => $game]);
}
}
My model Game.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Game extends Model
{
protected $casts = [
'mode' => 'array',
];
public function modes()
{
return $this->hasMany(Mode::class);
}
}
Finally my View view.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">View User's Teams & Manage</div>
<div class="panel-body">
<ul>
<li>{{$game->name}}</li>
<li>{{$game->mode}}</li>
<li>{{$game->size}}</li>
</ul>
</div>
</div>
</div>
</div>
</div>
#endsection
There are so many ways of printing an array, however, the simplest method is using the foreach loop.
#foreach ($game->mode as $mode)
<span>{{ $mode }}</span>
#endforeach
Or you can do something like {{ implode(", ", $game->mode) }} depending on your preference.
You are displaying the array like a string and there is the problem so you need to loop for the array of mode.
#for($i=0;$i<count($game->mode);$i++){ // here you print your result }
I was trying to show the name who have posted the post. It was working well. But after a few days, It is showing an error (ErrorException Trying to get property 'name' of non-object). I was searching for a solution for the last few days. And I have found laravel 8 introduced jetstream for authentication purposes. But I have already started with the laravel ui.
I have checked the model of mine. But I could not find anything which could solve the problem. Here are my codes.
view
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
#foreach ($posts as $post)
<div class="post-preview">
<a href="{{route('singlePost',$post-> id )}}">
<h2 class="post-title">
{{$post->title}}
</h2>
<h3 class="post-subtitle">
{!!$post->content!!}
</h3>
</a>
<p class="post-meta">Posted by
{{$post->user->name}}
on {{date_format($post->created_at,'F d,Y')}}
|| <i class="fa fa-comment" aria-hidden="true"></i> {{$post->comments->count()}}
</p>
</div>
<hr>
#endforeach
<!-- Pager -->
<div class="clearfix">
<a class="btn btn-primary float-right" href="#">Older Posts →</a>
</div>
</div>
</div>
</div>
<hr>
#endsection
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user(){
return $this->belongsTo('App\Models\User');
}
public function comments(){
return $this->hasMany('App\Models\PostComments');
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PublicController extends Controller
{
//This is the function which is showing posts
public function index(){
$posts = Post::all();
return view("welcome",compact('posts'));
}
public function contact(){
return view("contact");
}
public function about()
{
return view('about');
}
public function samplePost(Post $post){
return view('samplePost', compact('post'));
}
}
I have tried asking this question to everyone but nobody can see why I am trying to do it or why its not working but I will try my best to explain it properly this time.
I have a simple government page on my website that shows 3 panels in bootstrap with Higher Government, Senior Ministers and Junior Ministers. Inside each of them panels it shows a list of accounts assigned to that government rank.
Here is my government.blade.php:
#include('frontend.header')
<div class="col-md-12" style="padding-bottom:24px;">
<ul class="nav navtab nav-tabs" id="myTab" style="border-bottom:none;border-radius:1px;">
<li style="padding-right:13px;" class="active"><a style="" data-target="#higher_government_team" data-toggle="tab"><i class="fa fa-diamond" aria-hidden="true"></i> The Monarch/PM</a></li>
<li style="padding-right:13px;"><a style="" data-target="#senior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Seniors</a></li>
<li style="padding-right:13px;"><a style="" data-target="#junior_government_team" data-toggle="tab"><i class="fa fa-university"></i> Juniors</a></li>
</ul>
</div>
<div class="col-md-8">
<div class="tab-content">
<div class="tab-pane active" id="higher_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
higher gov here
</div>
</div>
</div>
<div class="tab-pane" id="senior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
senior gov here
</div>
</div>
</div>
<div class="tab-pane" id="junior_government_team">
<div class="panel panel-info">
<div class="panel panel-body">
#foreach ($juniorGovernment as $governmentMember)
{{ $governmentMember->user_id }}<br>
#endforeach
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
#include('frontend.footer')
Here is my controller for displaying the page:
<?php
namespace App\Http\Controllers\Frontend\User;
use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;
class GovernmentController
{
public function getView()
{
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
$seniorGovernment = Cache::remember('government.senior_government', 1, function() {
return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
});
$juniorGovernment = Cache::remember('government.junior_government', 1, function() {
return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
});
return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
}
}
Now as you can see, I only select the first record where government_type matches. But the issue is I have multiple government roles with that government type and I want to get all the account stats for all records with that government type. I have looked at others suggestions and none of them work, either throwing an error or don't do what I want to do.
Now, I have modals for each Roleplay and GovernmentRoles, I have posted them both below.
GovernmentRole:
namespace App\Database\Website\Roleplay;
use Eloquent;
class GovernmentRole extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_government_roles';
public $timestamps = false;
protected $fillable = [];
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
}
Roleplay:
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovernmentRole', 'government_id');
}
}
So what I am trying to achieve is not just grabbing all the Roleplay instances for the FIRST government role record in the database it finds but putting together ALL roleplay instances for ALL records that match government_type either higher_government, senior_ministers, or junior_ministers.
If I understand what you are asking, can you not do something like fetching the stats on your loop through in blade? For example (I removed the cache, its adding complexity to the question/answer without any benefit):
// controller
$higherGovernment = GovernmentRole::where('government_type', 'higher_government')->get();
// blade
#foreach($higherGovernment as $g)
{{ $g->id }}
{{ $g->name }}
#foreach($g->stats as $stat)
{{ $stat->id }}
{{ $stat->something }}
#endforeach
#endforeach
guys i am working on laravel project (i am beginner in laravel ) my role in this project is making the views and injecting the data ... while i am trying to inject Post in my view i got this error "Trying to get property of non-object " i am searching on the internet and some says that "may be the object returns null but i checked all the data comes from the object in the Controller and i found data by dd($post);"
here's the HomeController method that returns the post object
public function index()
{
$sliders = Slider::take(5)->get();
$post = Post::latest()->first();
$users = User::subscribed()->take(12)->get()->shuffle();
return view('frontend.pages.home2', compact('sliders', 'sliders', 'users', 'post'))->with('success',' success test');
}
and this is what i am trying to do in the view
#foreach($post as $pos)
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
{{$pos->body_ar}}
</p>
#endforeach
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
some text here to be displayed
<br>
<button type="button" class=" btn btn-primary">more</button>
</p>
<img class="nlpimage img-responsive " src="images/nnn.jpg">
</div>
and here's the Post.php class
namespace App\Src;
use App\Core\Traits\LocaleTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Post extends Model
{
use Notifiable, LocaleTrait;
public $localeStrings = ['title', 'body'];
public $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function gallery()
{
return $this->morphMany(Gallery::class, 'galleryable');
}
}
and the post table in the DB
enter image description here
Simply remove the foreach, because you are just passing one post instance to the view:
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
{{$post->body_ar}}
</p>
If you want to display more post, change to controller, to get more results (and use the foreach in your template, because now its an array):
$post = Post::latest()->take(3)->get();
$post = Post::latest()->first();
Reason: If the data returned is empty or mis-matched then alone you will be getting this error.
If you pass one row of data alone to the blade the foreach() seems to be an invalid option over there.
And that is the reason you will be getting this error over there.
Your blade will look like:
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
{{$post->body_ar}}
</p>
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
some text here to be displayed
<br>
<button type="button" class=" btn btn-primary">more</button>
</p>
<img class="nlpimage img-responsive " src="images/nnn.jpg">
</div>
Note: For passing of single value over to the blade you must not use foreach(). If it an array of values you can use foreach to iterate and then print the value over there.