vanusi's avatar

Passing data from database to view blade

I had an issue with passing data from mySql database to my view blade.

I have car_categories blade create which it's using Form:text to input it to Database, and how can I get the data to my car view using Form:select ?

Here's my car create blade code :

{!! Form::model($obj, [
'url' => $route,
'method' => $method,
'id' => 'carCreate',
]) !!} 
<div class="table-responsive">
<table class="table table-bordered" id="datatable" style="width: 100%">
    <thead>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Car Category:</strong>
                {!! Form::select('car_category_id', null, array('class' => 'form-control')) !!}
            </div>
        </div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary" >Submit</button>
{!! Form::close() !!}
</div>
</thead>
</table>

and here's my CarController Code : <?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Models\Car;
use App\Helpers\Enums\CarStatus;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Http\Controllers\Base\MasterController;
use Route;
use Illuminate\View\View;

class CarController extends MasterController
{
protected $indexView = 'car.index';
protected $createView = 'car.create';
protected $editView = 'car.create';
protected $routeBindModel = 'car'; //Route Model Binding name in RouteServiceProvider
protected $redirectPageWhenFormSuccess = 'car.index'; //Route Name
protected $title = 'car';

public function save(Request $request, $obj = null) {

if (!$obj) {
    $obj = new Car;
}
return $this->saveHandler($request, $obj);
}

//Must have this method if need datatable;
public function datatableBuilder($obj = null) {
return Car::query();
}

public function makeDatatable($obj) {

return Datatables::of($obj)
->addColumn('action', function ($model) {
        return $this->makeActionButtonsForDatatable($model);
})
->editColumn('status', function($model){
    return CarStatus::getString($model->gender);
})
->make(true);
}

public function render(View $view, $route = null, $obj = null, $method = 'POST') {
$statusList = CarStatus::getArray();
$view->with(compact('statusList'));
return parent::render($view, $route, $obj, $method);
}
}

and here's my MasterController code: <?php

namespace App\Http\Controllers\Base;

use Illuminate\Http\Request;
use App\Helpers\Traits\CRUDRenderHelper;
use App\Http\Controllers\Base\BaseController;

class MasterController extends BaseController
{
use CRUDRenderHelper;

protected $indexView;
protected $formView;

protected $routeBindModel; //Route Model Binding name in RouteServiceProvider
// If the route name is extremely long, please enable property below
// protected $updateFormRouteName = 'someModelName.update'; --> Route Name
// protected $saveFormRouteName = 'someModelName.save'; --> Route Name
// protected $redirectPageWhenFormSuccess = 'dashboard.index'; --> Route Name

public function index()
{
    return $this->render(view($this->indexView));
}

public function show($obj)
{

    $view = property_exists($this, 'detailView') ? $this->detailView : $this->indexView;
    return $this->render(view($view), null, $obj);
}

public function create()
{
    $view = property_exists($this, 'createView') ? $this->createView : $this->formView;
    $route = $this->getFormRoute();
    $this->setAction('New');
    $method = 'POST';
    return  $this->render(view($view), $route);
}

public function edit($obj)
{
    $view = property_exists($this, 'editView') ? $this->editView : $this->formView;
    $route = $this->getFormRoute($obj);
    $this->setAction('Edit');
    $method = 'PUT';
    return  $this->render(view($view), $route, $obj, $method);
}

public function store(Request $request)
{
    return $this->save($request);
}

public function update(Request $request, $obj)
{
    return $this->save($request, $obj);
}

public function destroy(Request $request, $obj)
{
    return $this->delete($request, $obj);
}

public function listDatatable($obj = null) {
    
    $builder = $this->datatableBuilder();
    return $this->makeDatatable($builder);
}
}

ex : I have 2 categories car Suv, Luxury, etc in Database. How can I get the value and show it at select list in my view.

0 likes
19 replies
tykus's avatar

Pass through an array cars to populate the select options as the second argument; the third argument will pre-select one option (for example in the edit view)

{!! Form::select('car_category_id', $car_categories, null, array('class' => 'form-control')) !!}
tykus's avatar

Yeah, you need to create that variable inside your create() controller method and pass it into the view; sorry, though that would be obvious.

tykus's avatar

IMO, your MasterController > CarController is a little inflexible, but yeah... or, if you prefer, you could view()->share() the variable from your AppServiceProvider

vanusi's avatar

@tykus_ikus sorry, I tried adding

$car_categories = CarCategory::all('name');
$view->with(compact('statusList', 'carCategory'));

under the public function render CarController

and as u said at Top

{!! Form::select('car_category_id', $car_categories, null, array('class' => 'form-control')) !!}

now it displays the data with this : {"name":"SUV"} {"name":"LUXURY"} {"name":"etc"}

any idea ?

InaniELHoussain's avatar

.@vanusi in your render funtion add it

public function render(View $view, $route = null, $obj = null, $method = 'POST') {
$statusList = CarStatus::getArray();
$car_categories = ;// set it in here
$view->with(compact('statusList', 'car_categories'));
return parent::render($view, $route, $obj, $method);
}
tykus's avatar

You want to CarCategory::pluck('name', 'id') which will give you an array of the form :

[
    1 => 'SUV',
    2 => 'Luxury',
    ...
]
vanusi's avatar

@tykus_ikus @InaniELHoussain sorry a bit issue, I cant save it. The car category id field is required. i try to dd($request) at function save, it show the category_id . it can be save if I remove public rules car_category_id => required, but it's not a good way haha..

tykus's avatar

@vanusi does the <select> tag name (car_category_id) match the rule? Are the <option> tags being properly formed (incl. value attributes?

Can you post the output of dd($request->all()) here?

vanusi's avatar

@InaniELHoussain it works when I remove the public rules car_category_id => required. if I remove it, it shows car_category_id NULL in my database. sorry for my bad English

vanusi's avatar

@tykus_ikus array:6 [▼ "_token" => "Ahd9zxeN9na0HdaMqfeYxWYM8nKQvYtWTnEMT1sq" "car_category_id" => "2" "year" => "1" "color" => "1" "plate_no" => "1212" "status" => "1" ]

tykus's avatar

So, the correct property is received. How/where are you defining the validation rules?

vanusi's avatar

@tykus_ikus here's howIi define the validation rules code at Car Model :

<?php

namespace App\Models;

use App\Models\Base\BaseModel;
use App\Models\CarCategory;
use App\Models\Fleet;

class Car extends BaseModel
{
public $timestamps = true;
protected $dates = ['created_at','updated_at'];
protected $fillable = ['year','color','plate_no','status'];
protected $guarded = ['created_at','updated_at'];
public static $rules = [ 
    'car_category_id' => 'required|integer',
    'year' => 'required|integer',
    'color' => 'required|integer',
    'plate_no' => 'required|alpha_num|between:4,25',
    'status' => 'required|integer',
];


public function carCategory() {

    return $this->belongsTo(CarCategory::class);
}
public function fleets() {

    return $this->hasMany(Fleet::class);
}
}
vanusi's avatar

@tykus_ikus Solved. I forget to add $obj->car_category_id = $request->car_category_id; under function save. thanks mate.

mojtabanaemi's avatar

hello for everyone I have form and I want to store gender(male/female) I can store it but when I want to riterive that in blade file it show all the data from my database column for example I had stored more than one value like male and female both of them when I riterive the gender it show both male and female

this is my code in blade file:

@foreach($photos as $photo)

{{ $photo->resized_name }}

@endforeach

Snapey's avatar

@mojtabanaemi start a new question rather than reply to one that is 3 years old.

When you do, also be clear about your question. You talk about male/female then show code for photos?

Please or to participate in this conversation.