three different table in one views laravel 5.2 - php

Hi I would like to display three different table in one views using laravel 5.2. but it seems i am having problem on it.
my HomeController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
public function index()
{
$about = DB::select('select * from about');
$teams = DB::select('select * from teams');
$services = DB::select('select * from services');
return view('master', ['about' => $about], ['teams' => $teams], ['services' => $services]);
}
}
in my views:
#foreach ($about as $abt)
<h4>{{$abt->title}}</h4>
<span class="semi-separator center-block"></span>
<p>{{$abt->description}}</p>
#endforeach
#foreach ($teams as $team)
<div class="creative-symbol cs-creative">
<img src="assets/images/new/{{$team->icon}}" alt="">
<span class="semi-separator center-block"></span>
<h4><b>{{$team->title}}</b></h4>
<p>{{$team->description}}</p>
</div>
#endforeach
i cant display the third one which is the $services. pls help me.
when i add the third one it will display an error

In Laravel 5.1, I found the following code in /vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:
if (! function_exists('view')) {
/**
* Get the evaluated view contents for the given view.
*
* #param string $view
* #param array $data
* #param array $mergeData
* #return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
*/
function view($view = null, $data = [], $mergeData = [])
{
$factory = app(ViewFactory::class);
if (func_num_args() === 0) {
return $factory;
}
return $factory->make($view, $data, $mergeData);
}
}
This is the function you are attempting to call. Notice how many arguments there are (there are 3). You are attempting pass in 4. I think what you're trying to do is something like this:
return view('master', [
'about' => $about,
'teams' => $teams,
'services' => $services
]);
This is now calling the same function, but only passing two arguments.

Please change this:
return view('master', ['about' => $about], ['teams' => $teams], ['services' => $services]);
to this:
return view('master', ['about' => $about, 'teams' => $teams, 'services' => $services]);

Related

How can I modify my Controller so that the query is limited to the user id?

I have my Controller set up as such:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Booking;
class eventController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$events = array();
$bookings = Booking::all();
foreach($bookings as $booking) {
'id' => $booking->id,
'title' => $booking->title,
'resourceId' => $booking->resourceId,
'start' => $booking->start_date,
'end' => $booking->end_date,
];
}
return view('home', ['events' => $events]);
}
}
Here I can pass everything from my DB into my view, but how can I filter these out such that only entries from a certain user_id is displayed? This is what my table looks like: https://imgur.com/AUZhA1L.
I have attempted to use the {user} blade but am stuck.
Change this line:
$bookings = Booking::all();
to this:
$bookings = Booking::where('user_id', 9)->get();
Or if you want to get the logged in user, you can use Auth.
Add this line after use App\Models\Booking;
use Illuminate\Support\Facades\Auth;
and then:
$bookings = Booking::where('user_id', Auth::id())->get();
In your User model add the following function (a user may have many bookings)
public function bookings(){
return $this->hasMany(Booking::class);
}
Get the logged in user by calling Auth::user();
like
$user = Auth::user();
$bookings = $user->bookings();

Laravel all() method on Model returning null within Collection

I am not sure, what is going on here. I have a collection of Model ID's but want to fallback on using all if specific ID's are omitted.
So I have this code:
use App\Models\Post;
function list($ids = [])
{
$posts = collect($ids)->whenEmpty(function ($posts) {
return Post::all()->pluck('id');
})->each(function ($item, $key) {
$post = Post::findOrFail($item);
});
}
Works fine if I pass in specific IDs via $ids. But when I leave it blank Post::all()->pluck('id'); inside of whenEmpty() returns empty. But if I call Post::all()->pluck('id'); outside the collection it works just fine. So I thought it might be some sort of scoping issue since its inside a closure, but changing it to:
use App\Models\Post;
function list($ids = [])
{
$posts = collect($ids)->whenEmpty(function ($posts) {
return \App\Models\Post::all()->pluck('id');
})->each(function ($item, $key) {
dd($item);
});
}
Is still showing up as "" If I dd() the whole collection its just:
[
0 => ""
]
So even providing the whole namespace isn't working. What am I missing here?
Here it's one approach more
function list(array $ids = [])
{
if(empty($ids)) $posts = Post::all();
else $posts = collect($ids)->map(function($id) {
return Post::findOrFail($id);
});
$posts->each(...); /* collection */
}
if you want to use whenEmpty()
function list(array $ids = [])
{
collect($ids)->map(function($id) {
return Post::findOrFail($id);
})->whenEmpty(function($posts){
return $posts = Post::all();
})->each(...);
}
I know this might not directly answer your question (because I would do this in a different way) but maybe it's helpful for you or others in the same situation.
What I would do is using a Request class to validate the introduced IDs like this:
use Illuminate\Validation\Rules\Exists;
class PostsRequests extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'ids' => ['array'],
'ids.*' => ['numeric', new Exists('posts','id')],
];
}
/**
* Handle a passed validation attempt.
*
* #return void
*/
public function passedValidation()
{
$this->ids = $this->validated()['ids'];
}
}
This way you make sure all the IDs introduced in the array exist in the posts table. Otherwise, the request fails.
Now that you know all the IDs are valid, you can simply check if the array is empty or not:
class PostController extends Controller
{
public function list(PostsRequests $request)
{
$posts = empty($request->ids) ? Post::all() : Post::whereIn('id', $request->ids])->get();
}
}
UPDATE
Since the array of IDs is not coming from a request, you can use a Validator in the controller itself:
use Illuminate\Validation\Rules\Exists;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
public function list(array $ids)
{
Validator::make($ids, [
'*' => ['numeric', new Exists('posts','id')],
])->validate();
$posts = empty($ids) ? Post::all() : Post::whereIn('id', $ids])->get();
}
}

Adding filter to eloquent resource to attach relationship conditionally

Laravel 5.8
PHP 7.4
I want to load the relationships conditionally like
http://127.0.0.1:8000/api/posts
and
http://127.0.0.1:8000/api/posts/1 are my end points now, I want to load comments like
http://127.0.0.1:8000/api/posts/?include=comments and
http://127.0.0.1:8000/api/posts/1/?include=comments
If the query parameter is there, only then it should load comments with posts or it should load only posts/post
I am doing this by referring a blog post
now, RequestQueryFilter
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
class RequestQueryFilter
{
public function attach($resource, Request $request = null)
{
$request = $request ?? request();
return tap($resource, function($resource) use($request) {
$this->getRequestIncludes($request)->each(function($include) use($resource) {
$resource->load($include);
});
});
}
protected function getRequestIncludes(Request $request)
{
// return collect(data_get($request->input(), 'include', [])); //single relationship
return collect(array_map('trim', explode(',', data_get($request->input(), 'include', [])))); //multiple relationships
}
}
and in helper
<?php
if ( ! function_exists('filter') ) {
function filter($attach)
{
return app('filter')->attach($attach);
}
}
?>
in PostController
public funciton show(Request $request, Post $post) {
return new PostResource(filter($post));
}
but when I am trying to retrieve
http://127.0.0.1:8000/api/posts/1/?include=comments getting no comments, with no error in log
A work around will be PostResource
public function toArray($request)
{
// return parent::toArray($request);
$data = [
'id' => $this->id,
'name' => $this->title,
'body' => $this->content,
];
$filter = $request->query->get('include', '');
if($filter){
$data[$filter] = $this->resource->$filter;
}
return $data;
}
I want to load the relationships conditionally like
Lazy Eager Loading using the load() call
The Lazy Eager Loading accomplishes the same end results as with() in Laravel, however, not automatically. For example:
?include=comments
// Get all posts.
$posts = Post::without('comments')->all();
if (request('include') == 'comments')) {
$posts->load('comments');
}
return PostResource::collection($posts);
Alternativelly, you could require the include query string to be an array:
?include[]=comments&include[]=tags
// Validate the names against a set of allowed names beforehand, so there's no error.
$posts = Post::without(request('includes'))->all();
foreach (request('includes') as $include) {
$posts->load($include);
}
return PostResource::collection($posts);
The call without() is only required in case you defined your model to automatically eager load the relationships you want to conditionally load.
With all data filtered in Controller, just make sure to display only loaded relations in your PostResource
public function toArray($request) {
$data = [...];
foreach ($this->relations as $name => $relation)
{
$data[$name] = $relation;
}
return $data;
}
I would create a custom resource for the posts with
php artisan make_resource
command.
E.g. PostResource.
The toArray function of the resource must return the data.
PostResource.php
public function toArray($request){
$data =['title' => $this->resource->title,
'body' => $this->resource->body,
'images' => new ImageCollection($this->whenLoaded('images')),
];
$filter = $request->query->get('filter', '');
if($filter){
$data['comments'] => new CommentCollection($this->resource->comments);
}
return $data;
}
Also, for collections, you need to create a ResourceCollection.
PostResourceCollection.php
class PostResourceCollection extends ResourceCollection
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request
* #return array
*/
public function toArray($request)
{
return [
'data' => $this->collection,
];
}
}
In your controller:
PostsController.php
//show one post
public function show(Post $post, Request $request)
{
/**this response is for API or vue.js if you need to generate view, pass the resource to the view */
return $this->response->json( new PostResource($post));
}
//list of posts
public function index(Request $request)
{
$posts = Post::all();
/**this response is for API or vue.js if you need to generate view, pass the resource to the view */
return $this->response->json( new PostResourceCollection($posts));
}
Partial Solution
It will need a small change in resource class
public function toArray($request)
{
// return parent::toArray($request);
$data = [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
'comments' => new CommentCollection($this->whenLoaded('comments')),
'images' => new ImageCollection($this->whenLoaded('images')),
];
return $data;
}
and it will load comments and images if loaded and that depends on the include query parameter, if that is not included, it will not load the relationship.
However,
In post collection
return [
'data' => $this->collection->transform(function($post){
return [
'id' => $post->id,
'title' => $post->title,
'body' => $post->body,
'comments' => new CommentCollection($post->whenLoaded('comments')),
'images' => new ImageCollection($post->whenLoaded('images')),
];
}),
];
will results in
"Call to undefined method App\Models\Customer::whenLoaded()",, if anyone suggests a complete solution, it will be a great help, if I will able to do, it I will update here.

Laravel get data from db array not working

When I run the code I get no error but the data I am trying to display is not displaying it's just blank.. can someone tell me what I'm doing wrong?
My controller:
public function openingPage($id) {
$this->getGames();
$games = $this->getGames();
return view('caseopener')->with('games',$games);
}
private function getGames() {
$games = array();
foreach ($this->data->items as $item) {
$game = new Game($item);
$games[] = array(
'id' => $game['id'],
'name' => $game['name'],
'price' => $game['price'],
'image' => $game['image'],
);
}
return $games;
}
The 'Game' Model that is used in 'getGames function':
class Game extends Model
{
private $id;
public $data;
public function __construct($id) {
parent::__construct();
$this->id = $id;
$this->data = $this->getData();
}
private function getData() {
$game = DB::table('products')->where('id', 1)->first();
if(empty($game)) return array();
return $game;
}
}
The view:
#foreach ($games as $game)
<div class="gold">$ {{ $game['price'] }}</div>
#endforeach
I think you are over-complicating things. You could simplify your flow like this:
Given your provided code, it seems like you are using a custom table name ('products') in your Game model. So we'll address this first:
Game.php
class Game extends Model
{
protected $table = 'products'; //
}
Now, it seems like you're searching an array of Game ids ($this->data->items). If so, you could make use of Eloquent for your query, specially the whereIn() method:
YourController.php
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', $games);
}
Optionally, if you want to make sure of just returning the id, name, price and image of each Game/product, you could format the response with API Resources:
php artisan make:resource GameResource
Then in your newly created class:
app/Http/Resources/GameResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class GameResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'image' => $this->image,
];
}
}
So now just update your controller:
YourController.php
use App\Http\Resources\GameResource;
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', GameResource::collection($games));
} // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Passing multiple parameters to controller in Laravel 5

In my application, a user has the ability to remind another user about an event invitation. To do that, I need to pass both the IDs of the event, and of the user to be invited.
In my route file, I have:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
In my view, I have:
{!!link_to_route('remindHelper', 'Remind User', $parameters = array($eventid = $event->id, $userid = $invitee->id) )!!}
In my controller, I have:
public function remindHelper($eventid, $userid)
{
$event = Events::findOrFail($eventid);
$user = User::findOrFail($userid);
$invitees = $this->user->friendsOfMine;
$invited = $event->helpers;
$groups = $this->user->groupOwner()->get();
return view('events.invite_groups', compact('event', 'invitees', 'invited', 'groups'));
}
However, when I hit that route, I receive the following error:
Missing argument 2 for App\Http\Controllers\EventsController::remindHelper()
I'm sure I have a formatting error in my view, but I've been unable to diagnose it. Is there a more efficient way to pass multiple arguments to a controller?
When you define this route:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
You are saying that a single URI argument will be passed to the method.
Try passing the two arguments, like:
Route::get('events/{event}/remind/{user}', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
View:
route('remindHelper',['event'=>$eventId,'user'=>$userId]);
Route :
Route::get('warden/building/{buildingId}/employee/{employeeId}',[
'uses'=>'WardenController#deleteWarden',
'as'=>'delete-warden'
]);
View :
Controller:
public function deleteWarden($buildingId,$employeeId){
$building = Building::find($buildingId);
$building->employees()->detach($employeeId);
return redirect('warden/assign/'.$buildingId)->with('message','Warden Detached successfully');
}
This is how you do it:
Click Here
Go to your controller and write code like following:
public function passData()
{
$comboCoder=['Bappy','Sanjid','Rana','Tuhin'];
$ffi=['Faisal','Sanjid','Babul','Quiyum','Tusar','Fahim'];
$classRoom=['Sanjid','Tamanna','Liza'];
return view('hyper.passData',compact('comboCoder','ffi','classRoom'));
}
/*
Again, in View part use:
(passData.blade.php)
*/
<u>Combocoder:</u>
#foreach($comboCoder as $c)
{{$c}}<br>
#endforeach
<u>FFI</u>
#foreach($ffi as $f)
{{$f}}<br>
#endforeach
<u>Class Room </u>
#foreach($classRoom as $cr)
{{$cr}}<br>
#endforeach
Route::get('/details/{id}/{id1}/{id2}', 'HomeController#SearchDetails');
//pass data like the below code
<a href="{{url("/details/{$orga_list->dcode}/{$orga_list->dname}/{$GroupHead}")}}"
target="_blank" > Details </a>
//controller write like the below code
public function SearchDetails($id, $searchtext,$grp_searchtext)
{
// get data like the below code
$data['searchtext'] = $searchtext;
$data['grp_searchtext'] = $grp_searchtext;
$data['id_is'] = $id;
}
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
Route::controller(BookController::class)->group(function () {
Route::get('author/{author_name}/book/{title}', 'show')
->name('book.show');
});
Now update the controller like:
app/Http/Controllers/BookController.php
namespace App\Http\Controllers;
use App\Models\Book;
use App\Models\Author;
use Illuminate\Http\Request;
class BookController extends Controller
{
public function show(Request $request, Author $author, Book $book)
{
return view('show',[
'book' => $book->show($request)
]);
}
}
Now update the book model:
app\Models\Book.php
namespace App\Models;
use App\Common\HasPdf;
use App\Common\HasImage;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Facades\URL;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Book extends Model
{
use HasFactory;
protected $guarded = [];
public function author() : BelongsTo
{
return $this->belongsTo(Author::class);
}
public function url()
{
return URL::route('book.show', [
'author_name' => $this->author->author_name,
'title' => $this->title,
]);
}
}
<h3>{{ $item->title }}</h3>
Hope it can help you.

Categories