Laravel Model to View - Undefined variable - laravel

I'm sure I'm missing something blindingly obvious but cannot see to get the division name to appear on my view.
It keeps returning Undefined variable: division_name
DIVISON.PHP (Model)
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
public function scopeGetDivisionName($query, $slug)
{
return $query->select('division_name')
->join('division_industry_job', 'division_industry_job.division_id', '=', 'divisions.id')
->join('industryjobs', 'division_industry_job.industry_job_id', '=', 'industryjobs.id')
->where('industryjobs.slug', '=', $slug);
}
}
JOBCONTROLLER.PHP (Controller)
public function showdivisionjob($slug)
{
$job = IndustryJob::where("slug", "=", $slug)->first();
$division_name = Division::getDivisionName($slug)->firstOrFail();
return View::make('job')->with('job', $job, $division_name);
}
JOB.BLADE.PHP (View)
{{$division_name->division_name}}
{{$job->job_title}}

You're not passing the variable to your view properly.
// This won't work
return View::make('job')->with('job', $job, $division_name);
It should be
return View::make('job')->with('job', $job)
->with('division_name', $division_name);
Or
return View::make('job', array(
'job' => $job,
'division_name' => $division_name
));

You can use also the compact method for passing variables to your view :
public function showdivisionjob($slug)
{
$job = IndustryJob::where("slug", "=", $slug)->first();
$division_name = Division::getDivisionName($slug)->firstOrFail();
return View::make('job', compact('job', 'division_name'));
}

Related

Laravel model function best prickets

im new in Laravel , I have an issue as below
I make in category model query to check is category is exist or not
as below
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
}
and my controller is
public function edit($id)
{
$dataView['category'] = Category::IsExist($id);
if(!$dataView['category'])
{
return view('layouts.error');
}else{
$dataView['title'] = 'name';
$dataView['allCategories'] = Category::Allcategories()->get();
return view('dashboard.category.edit')->with($dataView);
}
}
my problem is when I use method isEXIST if id not found it not redirect to error page but ween i remove ISEXIST AND replace it as below
$dataView['category'] = Category::where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
it work well .
can any one help me
That's because local scope should return an instance of \Illuminate\Database\Eloquent\Builder. You should remove the first() in the scope and put it in the controller.
Redefine your scope like so:
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC');
}
In your controller edit method:
$dataView['category'] = Category::IsExist($id)->first();
You can have a look to the doc for local scopes https://laravel.com/docs/8.x/eloquent#local-scopes

Create function with query in model, Laravel

I have a working function in my controller, but I want to place a part of the code in model, is repeatable and I want to use it in multiple controllers. but witch my current code is not working (no errors).
Controller
public function index(Request $request)
{
$query = new Question;
$query->select(
['questions.id',
'questions.free_text',
'questions.title',
'questions.created_at',
'lkp_answers.name as bestMatch',
]);
$query->with(['answer_history']);
$query->join('lkp_answers', 'lkp_answers.id', '=', 'questions.best_match');
$query->count_filter($query, $request); //here I try to use it
return response()->json($query->paginate($request->per_page));
}
Model
public function count_filter($query, $request){
if($request->sort_by){
$direction = ($request->sort_direction === 'false') ? 'asc' : 'desc';
if($request->sort_by === 'best_match'){
$query->orderBy('lkp_answers.name', $direction);
}else if ($request->sort_by === 'noneOfTheAbove') {
$query->withCount(['answer_history AS none' => function ($q) {
$q->where('answer_type', 'none');
return $q;
}])->orderBy('none', $direction);
} else if ($request->sort_by === 'skipped') {
$query->withCount(['answer_history AS skipped' => function ($q) {
$q->where('answer_type', 'skipped');
return $q;
}])->orderBy('skipped', $direction);
} else if ($request->sort_by === 'totalVotes') {
$query->withCount(['answer_history AS totalVotes' => function ($q) {
$q->where('answer_type', '!=','skipped');
return $q;
}])->orderBy('totalVotes', $direction);
}
else {
$query->orderBy($request->sort_by,$direction);
}
}
return $query;
}
The problem is that you defined the method to the model but you try to call it on an eloquent query. What you need to do is to use another variable for the query:
public function index(Request $request, Question $question)
{
$query = $question->newQuery();
$query->select(
['questions.id',
'questions.free_text',
'questions.title',
'questions.created_at',
'lkp_answers.name as bestMatch',
]);
$query->with(['answer_history']);
$query->join('lkp_answers', 'lkp_answers.id', '=', 'questions.best_match');
$question->count_filter($query, $request)
return response()->json($query->paginate($request->per_page));
}

Laravel 5.6 - request() with 2 variables

I am filtering results via request()->variable. When there is only one variable the view comes back as it should eg.../products/summer, displaying only products that belong to a certain season.
What i'm trying to do is call in a second variable /products/summer?product_category=shirts displaying the season products as above while filtering those that belong to a specific category (eg.shirts).
This is my controller part:
public function index()
{
if (request()->season) {
$products = Product::with('seasons')->whereHas('seasons', function ($query){
$query->where('slug', request()->season);
})->get();
$product_categories = ProductCategory::with('seasons')->whereHas('seasons', function ($query){
$query->where('slug', request()->season);
})->get();
$season = Season::where('slug', request()->season)->firstOrFail();
} **elseif (request()->product_category)** {
$products = Product::with('product_categories')->whereHas('product_categories', function ($query){
$query->where('slug', request()->product_category);
})->get();
$product_categories = ProductCategory::with('seasons')->get();
$season = Season::where('slug', request()->season)->first();
}......
return view('season')->with([
'products' => $products,
'product_categories' => $product_categories,
'season' => $season,
]);
Is there a way to include season and product_category in the elseif above so that it corresponds to summer?product_category=shirts ?
My nav link passes this:
href="{{ route ('season.index',['season' => $season->slug, 'product_category' => $product_category->slug])}}"
The route is:
Route::get('/products/{season?}', 'SeasonController#index')->name('season.index');
Thank you for your time.
I did not understand exactly what you need
If this code was not useful,plese explan more and i change it:
my view :
<a
href="{{ route ('season.index',['season' =>$season->slug, 'product_category' => $product_category->slug])}}"
>send</a>
my route :
Route::get('/products', 'SeasonController#index')->name('season.index');
SeasonController controler :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SeasonController extends Controller
{
public function index(Request $request)
{
if ($request->get('season'))
{
# do something
}elseif($request->get('product_category'))
{
# do something
}
else
{
# do something
}
}
}

Create Relationship inside the create function

I have a model that has a one to many relationship to the versions of the description.
In my Controller
$tag = Tags::create([
'name' => $request->get('name'),
'user_id' => \Auth::id(),
]);
$tag->update([
'content' => $request->get('description')
]);
In my Model:
public function setContentAttribute(string $value)
{
$this->versions()->create([
'user_id' => \Auth::id(),
'value' => $value
]);
}
So I can't put content directly as an attribute in the create method because there is no Model right now.
But is it possible to overwrite the create Method?
When I try to overwrite something like this in my Model it will do an infinity loop
public static function create($attr) {
return parent::create($attr);
}
So my question is if it is possible to have something like this:
$tag = Tags::create([
'name' => $request->get('name'),
'user_id' => \Auth::id(),
'content' => $request->get('content')
]);
and in the Model:
public static function create($attr) {
$value = $attr['content'];
$attr['content'] = null;
$object = parent::create($attr);
$object->content = $value;
$object->save();
return $object;
}
Update
I didn't overwrite the create method but called it customCreate. So there is no infinity loop anymore and I can pass all variables to the customCreate function that handles the relationships for me.
Solution
After reading the changes from 5.3 to 5.4 it turns out that the create method was moved so you don't have to call parent::create() anymore.
The final solution is:
public static function create($attr) {
$content = $attr['content'];
unset($attr['content']);
$element = static::query()->create($attr);
$element->content = $content;
$element->save();
return $element;
}
I don't see why not and you could probably implement a more general approach? Eg. checking if set{property}Attribute() method exists, if it does - use it to assign a value, if it doesn't - use mass assigning.
Something like:
public static function create($attr) {
$indirect = collect($attr)->filter(function($value, $property) {
return method_exists(self::class, 'set' . camel_case($property) . 'Attribute');
});
$entity = parent::create(array_diff_key($attr, $indirect->toArray()));
$indirect->each(function($value, $property) use ($entity) {
$entity->{$property} = $value;
});
$entity->save();
return $entity;
}
I haven't really tested it but it should work. I use something like this in one of my Symfony apps.

Laravel: Can't access methods in Model from Controller

I'm having an issue with one of my controllers accessing the methods within a model.
I have a controller (application>controllers>event.php) with an index method:
class Event_Controller extends Base_Controller {
public $layout = 'layouts.default';
public $restful = true;
public function get_index()
{
$category = (isset($_GET['category']))? $_GET['category'] : NULL;
$date = (isset($_GET['date']))? $_GET['date'] : NULL;
$county = (isset($_GET['county']))? $_GET['county'] : NULL;
$events = Event::get_event_list($category, $date, $county);
$this->layout->title = 'Events';
$this->layout->nest('content', 'event.index', array(
//'data' => $some_data
));
}
}
And the model (application>models>event.php):
class Event extends Eloquent{
public static function get_event_list($category = null, $month = null, $county = null)
{
$events = DB::table('events');
if($month)
$events->where('dtDateTime', 'LIKE', $month.'-%');
if($category)
$events->where('strCategories', 'LIKE', '%['.$category.']%');
if($county)
$events->where('strCounty', 'LIKE', '%'.$tag.'%');
return $events->order_by('dtDateTime', 'DESC')->get();
}
}
If I change the model name in the call to the method in the controller (ie Eventsx::....) I get an error that the model doesn't exist so I know it can find the model, however when I try and run this (or with a call to any other method in the Model), I get the error:
Call to undefined method Laravel\Event::get_event_list()
I have similar controllers accessing similar methods in their models but for some reason, it is not playing ball here. The controller can access methods in other Models with no issues.
Here are my routes:
Route::get('/events', array('as' => 'event', 'uses' => 'Event#index'));
Route::get('/events/(:any)', array('as' => 'event', 'uses' => 'Event#event'));
Can anyone see anything glaringly obvious that I'm doing wrong here?
Thanks
I worked it out. class Event is already taken by laravel. I renamed my model and everything worked fine

Resources