Laravel: How to pass a collection to view? - laravel

The $result variable displays the json-string correctly. And when I try to send the result to the view, I get an error.
$accreditations = Accreditation::with(['country'])->get();
$result = AccreditationResource::collection($accreditations);
//return $result;
//{"data":[{"id":5,"user_id":1,"login":"Admin","country_id":"4","country":{"id":4,"name":"Austria"}}]}
return View::make('accred_table', $result->login);
//Error 500: Property [login] does not exist on this collection instance.
Help me figure this out

$result is an array. So, there is no login as the error said. If you return only one record from AccreditationResource, you can use
return view('accred_table', ['login' => $result[0]['login']]);
In blade, you will have $login.

Related

How to add validate data search

I am using laravel for this project, i'm newbie at laravel then i want to add validate data if there is true then go to pdf blade, unless the data is false or wrong (i don't know what is it call so i named it True and False, but i hope you understand what i mean)
there is code in controller method search pdf
$id = $request->id;
$date = $request->date;
$pegawai = DB::table('pegawais')
->where('id', $id)
->whereDate('date', $date)
->get();
$pdf = PDF::loadview('pegawai_pdf', [
'pegawai'=>$pegawai
]);
return $pdf->stream();
and this is the output blade when i searched the data is true or exist
here
and this is the output blade when i searched but the data is false or not found data exist
here
fyi the data are fake data from seeder,
From your example, I will assume that you want to check if there is a result or not in $pegawai right? Then just count it.
if (count($pegawai) > 0) {
// show your pdf output here
} else {
// there is no data, do something here
}
to check this does not need to be a true false variable you can check this like this
if($pegawai){
$pdf = PDF::loadview('pegawai_pdf', [
'pegawai'=>$pegawai
]);
return $pdf->stream();
}else{
//show error here
}

Laravel 8 routing

I have a a function which gets all the data from the date inputted by the user and pass it to the table in view. In that table individual row of data retrieved from database has one anchor tag which carries id of each row in database to update the column in the database. All works fine but i'm having problem in redirecting to the table after update. i'm getting problem due redirecting to the page maturity_reqController/'whatever_ids' which doesnot exists but dont khow how to fix it.
My anchor Tag goes
Request
My Route goes
Route::get('maturity_reqController/{id}', [SettlementController::class,'maturity_reqController']);
my Controller goes
function maturity_reqController($id){
$forset = new Settlement();
$forset->org_document_id = $id;
$forset->save();
$data = Doc::find($id);
$data->status = "Maturity Requested";
$data->save();
return redirect('maturity_reqController');
}
You can try this
return redirect()->back();
for more details : laravel redirects
Add a name to your route like so:
Route::get(
'maturity_reqController/{id}',
[SettlementController::class,'maturity_reqController']
)->name('maturity.req');
Then whenever you need to link to that route use
Request
Edit: to redirect to that route:
return redirect()->route('maturity.req', ['id' => $items->id]);
More on Named Routes
Your Link
Request
web.php
Route::get('maturity_reqController/{id}', [SettlementController::class,'maturity_reqController'])->name('maturity_req');
Controller
function maturity_reqController($id) {
$forset = new Settlement();
$forset->org_document_id = $id;
$forset->save();
$data = Doc::find($id);
$data->status = "Maturity Requested";
$data->save();
return redirect()->route('maturity_req', ['id' => 'Your ID'])->with('success', 'Your Message');
}

How to Solve "Trying to get property of non-object" in Laravel?

If my code return null then it generates this error. If the code returns some data, then it works fine.
Controller
$profile_data= DB::table('partner_prefence')
->select('*')
->where('profile_id',$profile_id)
->first();
return view('partner_prefence',['profile_data' => $profile_data]);
View/Blade
#php($rel_status = explode(',', $profile_data->p_marital_status))
If $profile->p_marital_status has a value then there's no issue. The error only comes when its value is null.
Use optional()
https://laravel.com/docs/5.8/helpers#method-optional
If the given object is null, properties and methods will return null instead of causing an error.
{!! old('name', optional($user)->name) !!}
First $profile_data need to be checked whether it is empty or it has some data.
step2: Checking $profile_data object has property called p_material_status.
Step3: If the above both are true then try to explode the data otherwise return some error message and try not explode the data would be better.
<?php
$data = (($profile_data != null) && property_exists($profile_data->p_marital_status)) ? $profile_data->p_marital_status : null)
if($data){
$rel_status = explode(',', $data);
}else{
// Something else
}
?>
Depending on whether the entry is vital for the page to be rendered or not, you could either perform a check in the controller.
$profile_data = DB::table('partner_prefence')
->select('*')
->where('profile_id',$profile_id)
->firstOrFail()
Or allow the null value to pass on to the view and make a ternary check.
$profile_data ? $profile_data->p_marital_status : '';
References:
Ternary Operator
Retrieving Single Models
Simply use an isset() or != null on the sentence like this:
#php($rel_status = $profile_data ? explode(',', $profile_data->p_marital_status?: '')) : [];

Laravel 5.4 Undefined Variable from controller to view

I recently got started with Laravel 5.4, I'm familiar with 5.3. I'm trying to pass a variable from my controller to the view and keep getting an "Undefined variable $savedStores".
public function index()
{
//
$stores = Store::where('id as user_id')->get();
return view('home')->with('savedStores', $store);
}
That is my controller code.
In my view, I have
#if(count($savedStores)>0)
#foreach($savesStores as $savedStore)
<p>{{$savedStore -> name}}</p>
#endforeach
#endif
return view('home',['savedStores'=>$stores]);
spelling mistake chane $store to $stores
Just change your code:
from:
$stores = Store::where('id as user_id')->get();
to:
$stores = Store::where('id',$some_id_value)->get();
Or you can get all store records by:
$stores = Store::all();
You are passing the variable to view in correct manner.
More details check here:
https://laravel.com/docs/5.4/views
Actually with method used for session data.
You can pass variables to view.
return view('home',['savedStores'=>$stores]);
or
return view('home',compact('stores')); // as store variable.
Try this one,
public function index()
{
$stores = Store::select('*','id as user_id')->get();
dd($stores);//see query result, if you get correct result here, just remove this line
return view('home')->with('savedStores', $stores );
}

Laravel Eloquent - Update() function always return true

Consider the code
return User::find($user_id)->update($data_array)?true:false;
if $data_array have some columns that are not present in User related table.
then also above statement return true.
e.g: $data_array=['not_in_the_table'=>'value'];
return User::find($user_id)->update($data_array)?true:false;
returns true. What is the condition when update returns 0 i.e. false?
If you use where('id','=',$user_id) like below instead of find($id), you will get error like Column not found for the columns that are not present in User related table. So it is best way to do this :
User::where('id','=',$user_id)->update(['column_name'=>'value']);
Instead of :
User::find($user_id)->update($data_array)?true:false;
Update method always return int. For more info Check Here
or If you want to update the the record by using Object Relation Mapping way then you can do like this :
$user = User::find($user_id) ;
$user->column_name = 'value';
if($user->save()){
//do something when user is update
}else{
// do something wehn user is not update
}
You cannot get error into false there because validation of Laravel use library.
For Laravel 4.2
public function update($user_id) {
$data_array = Input::all();
$validator = Validator::make(
$data_array,
array('name' => 'required|min:5')
);
if ($validator->passes()) {
// success as true
User::find($user_id)->update($data_array)
} else {
//failed as false
}
}
For more information about validator
I hope this help you

Resources