简体   繁体   中英

How can I Retrieve only a Row from a table in Laravel

I am new in laravel and i am developing an application that I need to display the persons first and last name upon registering on my system. But I am finding it it hard to achieve this instead my code retrieves all the first and last names from my table if i use the instance $contact =contacts::all();

My table named contact has fields like fname, lname,email,phone, body, updated_at,...

I have tried using the ...all()->pluck() to select only the first name and last name but my views displays everything first and last name from the table. I can do it in my views but i need your help in my controller.

Here is my controller

$contact =contacts::all()->pluck('lname','fname'). 

Anyone with an idea please

-> contacts::all() --- This will result all the data in contacts model

-> contacts::first() --- This will result only single row. please add a where condition with this for required result. eg contacts::where('name','=','abc')->first();

contacts::all() will retrieve every single row. If you want to limit the selection to contacts that only have a certain first/last name, then you'll want to use where and get() , which will only get those particular rows:

$fname = 'John';
$lname = 'Doe';
contacts::where('fname', $fname)->where('lname', $lname)->get();

The two variables, of course, would be populated with whatever you're looking for. You can also pass in a comparison as the second parameter, in case you want to check for not equals, LIKE (good for case insensitive searches or wildcard searches), or greater than/less than for numbers and dates.

contacts::where('fname', '=', $fname)->where('lname','=', $lname)->get();

Note that this will bring up everyone with the name John | Doe. It may not be the person who just registered. For that, you'll want to save the user ID somewhere such as in the session after they register, and instead look for that id, which will bring up only 1 record instead of a collection of records that get() would provide.

contacts::find($id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM