I'm using the Discord API to get the members on a Discord guild to display 10 randoms users and display it in the view with blade using the foreach method.
I'm getting the JSON from the API, getting the members array of it and sclicing it to return only 10 members to send it from the controller to the view.
The problem is that, when I want to parse it and use an element of the array (avatar_url), it's not working and I'm getting this error message: Trying to get property 'avatar_url' of non-object
Here is my controller
class IndexController extends Controller {
...
/**
* Function to get 10 random players on fivem
* #return array
*/
private function getServerPlayers() {
$request = file_get_contents('https://discordapp.com/api/guilds/683766194884575355/widget.json');
$decoded = json_decode($request, true)['members'];
return array_slice($decoded, 0, 10);
}
/**
* Return index view
* #return Factory|View
*/
public function index() {
return view('index')->with('players', $this->getServerPlayers())->with('clients', $this->getServerClients())->with('members', $this->getDiscordMembers());
}
}
Here is my view
<div class="row">
<div class="col-lg-12">
<div class="tab-content" id="pills-tabContent">
<div class="tab-pane fade show active" id="pills-all-bets" role="tabpanel"
aria-labelledby="pills-all-bets-tab">
<div class="responsive-table">
<table class="table">
<thead>
<tr>
<th scope="col">Nom du joueur</th>
<th scope="col">Statut</th>
</tr>
</thead>
<tbody>
#foreach($players as $player)
<tr>
<td><img src="{{ $player->avatar_url }}">{{ $player->username }}</td>
<td>En ligne</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
I think that the problem is kind of dumb but I'm blocked on it, I need some help !
Thanks.
You should use avatar_url like this:
<td><img src="{{ $player['avatar_url'] }}">{{ $player['username'] }}</td>
because what you pass to view is an array, not an object.
The problem is that json_decode returns an array and not an object.
You can pass the arguments to the view using:
return view('index',[
'players' => $this->getServerPlayers(),
'clients' => $this->getServerClients(),
'members' => $this->getDiscordMembers(),
]);
And then display them in the view using:
<img src="{{ $player['avatar_url'] }}">{{ $player['username'] }}
Related
whats wrong why in blade don't want to show the LEVEL name
controller:
$streams=Stream::with('level')->get();
return view('streams.index',compact('streams'));
Stream Model:
public function level()
{
return $this->belongsTo('App\Models\Level', 'level_id');
}
Level Model:
public function stream()
{
return $this->hasMany('App\Models\Stream', 'level_id');
}
Blade Index:
#foreach($streams as $stream)
<tr>
<th scope="row">#</th>
<td>{{$stream->name}}</td>
<td>{{$stream->code}}</td>
<td>
{{$stream->level->name}}
</td>
<td>
<tr/>
#endforeach
Also tried:
#foreach($streams as $stream)
<tr>
<th scope="row">#</th>
<td>{{$stream->name}}</td>
<td>{{$stream->code}}</td>
#foreach($stream as $level)
<td>
{{$level->name}}
</td>
#endforeach
<td>
<tr/>
#endforeach
Error:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\project\sms\resources\views\streams\index.blade.php)
DD result:
[{"id":3,"name":"Class A","code":"GRC0001A","uuid":"X9HG9zc7ceTlhdfF1fN1wAer1cHP1MhfuM7GHBSqNogYSo3bsGmpTl06iJQyyKp3QMrkHe1VyiTxeKFa49wC7W5BY3E3kFZkpF1D","level_id":1,"created_at":"2020-06-14T10:58:28.000000Z","updated_at":"2020-06-14T11:39:54.000000Z","level":{"id":1,"name":"YEAR 7","code":"CODE1","uuid":"X9HG9zc7ceTlhdfF1fN1wAer1cHP1MhfuM7GHBSqNogYSo3bsGmpTl06iJQyyKp3QMrkHe1VyiTxeKFa49wC7W5BY3E3kFZkpF1D","created_at":"-000001-11-30T00:00:00.000000Z","updated_at":"-000001-11-30T00:00:00.000000Z"}},{"id":4,"name":"Class B","code":"GRC0001A","uuid":"gq2kZZikN76XEa4pQWsyAZBMxjKeHBJt0a840ZMSiuHGztuhYT0G6q5WcGgp8z6BD6nx0WSrrOTvEb4iQ0ewyB9Fa1M54CAv8HS2","level_id":null,"created_at":"2020-06-14T10:58:36.000000Z","updated_at":"2020-06-14T11:39:59.000000Z","level":null}]
Your first Blade template is almost correct.
The issue is that one or more of your records has no Level assigned (level_id=null), but you're still trying to pull the name property from $stream->level, which is null.
Simply add a check for $stream->level before trying to access/print its properties. For example:
#if($stream->level)
{{ $stream->level->name }}
#endif
or
{{ $stream->level ? $stream->level->name : 'No Level Attached' }}
or
{{ optional($stream->level)->name }}
etc.
So guys I add pagination to my project and I'm almost finishing it, witch by the way is my first project ever, and all I need to do right now is to set pagination by created_at.So I need to put posts from the same day on same page link. Right now it shows me posts from different days on one page. And after that I just need to show price sum of that day. If you know please help me, this would be my first project as a student, I'm still learning. Thank you !!
Here is my HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Post;
use DB;
use Auth;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$posts = Post::where('user_id', Auth::id())->orderBy('created_at', 'DESC')
->paginate(3);
return view('home')->with('posts', $posts);
}
}
Here is my home.blade.php
#extends('layouts.theme')
#section('content')
<style>
body{
margin: 0;
background-color: #EBEBEB;
}
</style>
<div class="mainl">
<div class="row">
<div class="columna">
<h1>{{ Auth::user()->name }}</h1>
<hr>
</div>
<div class="columns">
<a href="{{ route('logout') }}" id="logout"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('LOGOUT') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
</div>
</br></br></br>
#if(count($posts)> 0)
<table>
<thead>
<tr>
<th>BR.KESICE</th>
<th>IME I PREZIME</th>
<th>BR.TELEFONA</th>
<th>POSAO</th>
<th>CIJENA</th>
<th>PLACANJE</th>
<th>POPUST</th>
<th>DATUM PREUZ.</th>
<th>DATUM IZDAV.</th>
<th>SMJENA</th>
<th>RADNIK</th>
<th>STATUS</th>
<th>IZMIJENI</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->br_kesice}}</td>
<td>{{$post->ime}}</td>
<td>{{$post->br_telefona}}</td>
<td>{{$post->posao}}</td>
<td>{{$post->cijena}}</td>
<td>{{$post->placanje}}</td>
<td>{{$post->popust}}</td>
<td>{{$post->datum_preuz}}</td>
#if($post->status == 1)
<td>/</td>
#else
<td>{{$post->datum_izdav}}</td>
#endif
<td>{{$post->smjena}}</td>
<td>{{$post->radnik}}</td>
<td>
#if($post->status == 0)
<span class="label label-primary" id="statusdeaktivan">Deaktivan</span>
#elseif($post->status == 1)
<span class="label label-success" id="statusaktivan">Aktivan</span>
#elseif($post->status == 2)
<span class="label label-danger" id="statusdeaktivan">Rejected</span>
#else
<span class="label label-info" id="statusdeaktivan">Deaktivan</span>
#endif
</td>
#if($post->status == 3)
#else
<td><i class="far fa-edit"></i></td>
#endif
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>UKUPAN IZNOS: {{ Auth::user()->posts->sum('cijena')}}€</th>
<th>KARTICA: {{ Auth::user()->posts->where('placanje', 'Kartica')->sum('cijena')}}€</th>
<th>GOTOVINA: {{ Auth::user()->posts->where('placanje', 'Gotovina')->sum('cijena')}}€</th>
<th>VIRMAN: {{ Auth::user()->posts->where('placanje', 'Virman')->sum('cijena')}}€</th>
</tr>
</tfoot>
</table>
{{ $posts->links()}}
#else
<p>Trenutno nema unosa.</p>
#endif
</div>
#endsection
And I found something from past questions here in stack overflow and it's working but I have a problem with that, so
public function index()
{
$posts = Post::where('user_id', Auth::id())->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))->get();
return view('home')->with('posts', $posts);
}
When I add this ->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))->get(); it shows me all posts from past 10 days but after that 10 days nothing, could I use this but to sort it by all days, not to set maximum days?
I also add this code to my price sum and it is working but as I said just for past 10 days
<tfoot>
<tr>
<th>UKUPAN IZNOS: {{ Auth::user()->posts->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))->sum('cijena')}}€</th>
<th>KARTICA: {{ Auth::user()->posts->where('placanje', 'Kartica')->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))->sum('cijena')}}€</th>
<th>GOTOVINA: {{ Auth::user()->posts->where('placanje', 'Gotovina')->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))->sum('cijena')}}€</th>
<th>VIRMAN: {{ Auth::user()->posts->where('placanje', 'Virman')->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))->sum('cijena')}}€</th>
</tr>
</tfoot>
Thank you again and I would really appreciate it if you help me with this. It's my first project and I'm very happy about it.
What your current code is doing is taking all the posts, sort it by created_at and then show 3 at a time. It doesn't care about what day it is or how many $post are there for that particular day.
What I understand that, you want to do is to show it by date. In that case, your query should filter based on date.
What you need to do is pass the date to the controller and fetch only posts from that day. It is a bit tricky. You need to pass today's date to controller.
In HTTP GET method your URL should contain the date. For example, it can be something like http://example.com/index?date=20190716. Notice that "date=20190716" part. You can get this in controller. Then you can get the posts of that day by writing,
$date = new Carbon(request('date'));
$posts = Post::where('user_id', Auth::id())
->whereDate('created_at','=',$date)
->orderBy('created_at', 'DESC')
->paginate(3);
Now, what it will do is get only the posts from 16th July, 2019.
This is the main idea. How you pass the date is entirely on you. You can do that in several ways. You can use JS, HTTP GET method and HTTP POST method.
Try
public function index()
{
$posts = Post::where('user_id', Auth::id())->get();
return view('home')->with('posts', $posts);
}
Try this also, I hope helps you
public function index()
{
$dateFromUrl = \Carbon\Carbon::createFromFormat('d/m/Y', request()->date);
$posts = Post::where('user_id', Auth::id())->where('created_at',$dateFromUrl)->orderBy('created_at', 'DESC')
->get();
$sum = 0;
foreach($posts as $post){
$sum+=$post->price;
}
return view('home', compact("posts","sum"));
}
I have 6 types of users in my application. For one view, I want to check if any one of the given two types of users are logged in. If they are, then show this item.
This is working
#can('admin-controller')
<div class="custom-submit-button-group">
View All Messages
</div>
#endcan
But, I want this to work. I want to show the div to these two user types.
#can('admin-controller' || 'general-controller')
<div class="custom-submit-button-group">
View All Messages
</div>
#endcan
But none of them can see this item.
I can use Auth::check() but I only wanted to use #can
Try #canany.
<table>
<tr>
<th>...</th>
#canany(['edit_post', 'delete_post'])
<th>Actions</th>
#endcanany
</tr>
<tr>
<td>...</td>
#canany(['edit_post', 'delete_post'])
<td>
#can('edit_post')
<button>Edit</button>
#endcan
#can('delete_post')
<button>Delete</button>
#endcan
</td>
#endcanany
</tr>
</table>
You can use Gate Facade like this:
#if(Gate::check('update-post') || Gate::check('update-post2'))
#endif
And you can define your permissions in App\Providers\AuthServiceProvider liek this:
public function boot()
{
$this->registerPolicies();
Gate::define('update-post', function ($user, $post) {
return $user->id == $post->user_id;
});
}
OR
#if($user->can('perm1') || $user->can('perm2'))
// do something
#endif
In my ImageController, I've moved an image to a directory and saved the image path in a table in database as,
public function store(Request $request)
{
$new_country = new SelectCountry();
$message = [
'required' => "This field can not be empty",
];
$this->validate($request, [
'country_name' => 'required',
'alternate_title' => 'required',
'country_flag' => 'required',
], $message);
$new_country->country_name = $request->country_name;
$new_country->alternate_title = $request->alternate_title;
if($request->hasfile('country_flag'))
{
$country_flag_image = $request->file('country_flag');
$country_flag_name = $country_flag_image->getClientOriginalName();
$extention = $country_flag_image->getClientOriginalExtension();
$dirpath = public_path('assets/images/country/');
$country_flag_image->move($dirpath,$country_flag_name);
$new_country->country_flag_path = $dirpath.$country_flag_name;
}
$new_country->save();
return redirect()->route('admin.country');
}
Now I want to use the path and display the image along other informations. I've used the following code to return view,
public function select_country()
{
$countries = SelectCountry::all();
return view('auth.select_country')->with('countries',$countries);
}
And in the view, I've used following code to display datas stored in the database,
<table class="table-hover table-responsive container-fluid col-xs-12 col-sm-12">
<thead>
<tr>
<th>Country Name</th>
<th>Alternate Title</th>
<th>Country Flag</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($countries as $country)
<td>{{ $country->country_name }}</td>
<td>{{ $country->alternate_title }}</td>
<td><img src="{{ $country->country_flag_path }}"></td>
<td>
<a type="button" href="" class="btn btn-warning btn-xs">Update</a>
<a type="button" href="" class="btn btn-danger btn-xs">Delete</a>
</td>
#endforeach
</tbody>
The problem is the image is not displayed while other informations are displayed. The src attribute in img tag is returning path but not directory.
If there is any solution, please tell me. Thanks.
I think your issue lies with where you are setting the storage folder. Laravel with automatically reference the public folder for storage of images etc so there's no need for the public_path function.
Try setting your $dirpath to just $dirpath = "/asset/images/country" as Laravel looks inside public by default. You can then reference it by doing <img src="{{ $country->country_flag_path }}">
Then upload a new image and see what the database has the path set to, hopefully it should be a bit more normal :)
Please note that my original answer of:
Try setting your $dirpath to just $dirpath = "images/country" as Laravel looks inside public by default. You can then reference it by doing <img src="{{ asset($country->country_flag_path) }}">
Should still work as it's how I've always done it :)
I'm trying to get pagination working in my joompla component admin page (table of records from database).
I'm using the standard method found on the net, so in my view class I have:
function display($tmpl=NULL)
{
$this->tabela = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
...
and then in my default template for this view:
<tfoot>
<tr>
<td colspan="7" >
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
but the pagination is not showing up. In the place where it should occur I can only see this (in website's HTML):
<div class="pagination pagination-toolbar">
<input type="hidden" name="limitstart" value="0">
</div>
How can I get this pagination work?