Call To A Member Function On String - laravel

Hello Guys I Have This Function In My Model
public function photo () {
return $this -> photo;
}
And I Called The Function From My Blade
{{$model = \App\Models\mainCategory::class}}
<td> <img style="width: 150px; height: 100px;" src="{{asset('assets/images/main-categories/' . $model -> photo() // Here I Have an Error `Call to a member function photo() on string` )}}"></td>
I Have This Error Call to a member function photo() on string

use App\Models\mainCategory;
class YourController extends Controller
{
public function index(){
return view('your_view', ['category' => mainCategory::first() ];
}
}
Then in your blade file, you do:
$category->photo
Instead of your current model->photo()

This line {{$model = \App\Models\mainCategory::class}} is wrong. You have first to retrieve the model from the database, to use the model attributes.
For example
{{$model = \App\Models\mainCategory::first()}} or
{{$model = \App\Models\mainCategory::find($id)}}.
Another thing to point, since you have the attribute photo already existing, why would write a method, that returns the same thing. You can use $model->photo directly.
Another thing, it's not recommended to retrieve data from the database, while you're in the view, you have the controller to do so.

Related

Laravel collection display and short issue

Hello guys!
I have a a little problem with collections. I have never worked with these. I would like to display a collection at my welcome blade but there is a problem. My collection is not in the contrroller, the collection's place is in the App/Repositories/xyz.php and in a function. How can i pass this function to the controller and after show it at the welcome blade??
App/repositories/xyz.php
public function getcars(): Collection
{
return collect([
new Car(...)
)];
controller
public function __invoke(): View
{
return view('welcome', ['cars' => collect([
new Car() ------> I would like to put datas from xyz.php repo here
new Car()
new Car()
....
And welcome.blade file where i would like to display
<div class="car-list">
<h2>{{ $title }}</h2>
#foreach($cars as $car)
<x-car :car="$car" />
#endforeach
</div>
You could do that in many ways:
Creating new instance
use App\repositories\Xyz;
public function __invoke(): View
{
$repo = new Xyz();
return view('welcome')->with('cars', $repo->getcars());
}
Pulling your class from the container
use App\repositories\Xyz;
public function __invoke(): View
{
$repo = app(Xyz::class);
return view('welcome')->with('cars', $repo->getcars());
}
Using dependency injection to resolve it from container
use App\repositories\Xyz;
protected Xyz $repo;
public function construct(Xyz $xyz): View
{
$this->repo = $xyz;
}
public function __invoke(): View
{
return view('welcome')->with('cars', $this->repo->getcars());
}
I believe from your Controller file, you can create an object property of your Repository via __construct() method like this:
protected MyRepository $myRepository;
public function __construct(MyRepository $myRepository)
{
$this->myRepository = $myRepository;
}
Then, you can call $this->myRepository's method from there, for example like getting records, etc. Then you can pass the result to your view.

Export Excel in Laravel

**I have a problem with passing parameters on export file, I want to filter the export according to date selected on page. Hope you help me with this issue. Thanks **
This is my ExportController, I request data from form to my controller to give the export collection a date.
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use App\Exports\ExportAttendance;
use Maatwebsite\Excel\Facades\Excel;
class ExportController extends Controller
{
public function export(Request $request)
{
return Excel::download(new ExportAttendance($request->input('min'),$request->input('max')),'Attendance.xlsx');
}
}
This is my ExportAttendance.php, this is responsible for the exportation of collections. On the query function I want to filter the data according on the date requested on the controller. How could I passed a data from controller to my Export.php, I did used constructors but it always return errors.
public function headings():array{
return[
'Name',
'In (AM)',
'Out (AM)',
'In (PM)',
'Out (PM)',
'Meeting',
'Task',
'Note',
'Total Hours',
'Date'
];
}
public function query()
{
$start = "2021-06-14";
$end = "2021-06-14";
return Attendance::select('Name','InAm','OutAM','InPM','OutPM','Meeting','SpecialTask','Undertime','TotalHours','Date')->whereBetween('Date',[$start,$end]);
}
public function collection()
{
return Attendance::all();
}
public function map($attendance):array
{
return[
$attendance->Name,
$attendance->InAM,
$attendance->OutAM,
$attendance->InPM,
$attendance->OutPM,
$attendance->Meeting,
$attendance->SpecialTask,
$attendance->Undertime,
$attendance->TotalHours,
$attendance->Date,
];
}
Instead of passing the $request object to the export class. You can simply use the request helper method.
public function query()
{
return Attendance::select('Name','InAm','OutAM','InPM','OutPM','Meeting','SpecialTask','Undertime','TotalHours','Date')
->whereBetween('Date',[request('start'), request('end')]);
}
Passing parameters is supposed to work too. Pls let me know what errors you see so I can update my answer.
I used Constructor
public function query()
{
$start = "2021-06-14";
$end = "2021-06-14";
return Attendance::select('Name','InAm','OutAM','InPM','OutPM','Meeting','SpecialTask','Undertime','TotalHours','Date')->where('Date','=',$this->year);
}
And this is my controller,
public function export(Request $request)
{
ob_start();
$datestart = $request->input('min');
$datestart = ob_get_contents();
return Excel::download(new ExportAttendance($datestart),'Attendance.xlsx');
ob_end_flush();
}
Another problem arise, when I used ob_end_clean() all my variable values returned nulls.

Laravel using where clause on Views

I'm newbie on Laravel.
I can send data like that:
public function index()
{
$InboxNew = Models\Inbox::where('read', false)->get();
$InboxMarkedAsRead = Models\Inbox::where('read', true)->get();
return view('dashboard.inbox', compact('InboxNew', 'InboxMarkedAsRead'));
}
I want to get data in view like that but gives some errors:
public function index()
{
$Inbox = Models\Inbox::all();
return view('dashboard.inbox', compact('Inbox'));
}
In view:
#if($Inbox->where('read', false)->get())
...
#endif
Your controller :
public function index()
{
$Inbox = Models\Inbox::all();
return view('dashboard.inbox', compact('Inbox'));
}
In blade you can achieve your data like this way :
#foreach($inbox as $query)
#if($query->read == false)
//
#endif
#endforeach
Problem with your code is that you have already called all() method on the Models\Inbox. What all() do is to simply call the get() method on model without applying any conditions.
You either need to define only a model (via query() method:
// Controller
public function index()
{
$Inbox = Models\Inbox::query();
return view('dashboard.inbox', compact('Inbox'));
}
and fetch it later with where clauses In view:
#if($Inbox->where('read', false)->get())
...
#endif
OR
You can do it in a cleaner way, which is to fetch the data in controller and use the view only to show the data
You either need to define only a model (via query() method:
// Controller
public function index()
{
$Inbox = Models\Inbox::where('read', false)->get();
return view('dashboard.inbox', compact('Inbox'));
}
and fetch it later with where clauses In view:
#if($Inbox)
...
#endif
PS: To check if a record exists, use exists() method instead of get() e.g $Inbox->exists()

Pass variable from one method to another in same controller Laravel

I need to pass select option value from store method to show
i need to pass the $typeg value to show method
public function store(Request $request ) {
$typeg = $request->input('type');
}
public function show($id) {
dd($this->store($typeg));
}
i get
Undefined variable:
or
Too few arguments to function app\Http\Controllers\appController::show(), 1 passed and exactly 2 expected
Try this
on the first function you have some variable witch you want to pass it to another function\method
Than you need to use $this and the name of the other method you'd like to pass the var too something like this.
public function oneFunction(){
$variable = "this is pretty basic stuff in any language";
$this->anotherFunction($variable)
}
public function anotherFunction($variable){
dd($variable);
}
Store your data on session (or somewhere else like cookie, cache, database). So you can reach the data later.
class SomeController extends Controller {
public function store(Request $request ) {
session(["typeg"=>$request->input('type')])
}
public function show($id) {
dd(session("typeg"));
}

recall the construct in codigniter

How to recall the construct as it contains all the required data for the page?
class Abc extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('xyz_m');
$this->data['info'] = $this->xyz_m->get(); //get data
}
public function 123()
{
/*view page code*/
}
public function 456()
{
/*insert code here*/
$this->123(); // redirect, need to load 123() with updated data from construct.
}
}
So, how do you make the __construct initiate again so you get a new updated results from database?
You should name your methods with letter first i.e. there is convention for method names uses descriptive words getProducts() or get_books or you will get PHP error for using numbers as method names. So in your case method names should be like a123() or b_456().
Second thing, regarding your need in question, since you assign data from DB using model to array $this->data, you would use it like:
class Abc extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('xyz_m');
$this->data['info'] = $this->xyz_m->get(); //get data
}
public function a123()
{
$this->load->view('a123_view', $this->data);//loading file APPPATH . 'a123_view.php' and passing created array to it
}
public function b_456()
{
/*insert code here*/
$this->a123(); // redirect, need to load 123() with updated data from construct.
}
}
In your APPPATH . 'a123_view.php':
<?php var_dump($info);//here you would call key of array you passed from controller as variable ?>
Check basics in CodeIgniter documentations. All this is described in General Topics section.

Resources