Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all fields from db model in Laravel

After creating model, when I try to get his attributes, i get only fields in database that are filled.

    ----------------------------------------------
DB: | id | shopID | name | bottleID | capacity |
    ----------------------------------------------
    | 1  | 8      | Cola |  3       |          |
    ----------------------------------------------

In this case I need capacity attribute too, as empty string

public function getDrinkData(Request $request)
{
    $drink = Drink::where('shopId', $request->session()->get('shopId'))->first();

    if($drink) {
        $drink = $drink->attributesToArray();
    }
    else {
        $drink = Drink::firstOrNew(['shopId' => $request->session()->get('shopId')]);
        $drink = $drink->attributesToArray(); // i want to get even empty fields
    }
    return view('shop.drink')->(['drink' => $drink])
}

But for later usage (in view) I need to have all attributes, including empty ones. I know that this code works as it should, but I don't know how to change it to detect all attributes.

like image 275
Ivan Vulović Avatar asked Jun 15 '16 12:06

Ivan Vulović


People also ask

How can I get specific field in laravel?

Select specific columns with Laravel Eloquent To get all of the columns from the users table, we would use the following: $user = User::where('username', 'bobbyiliev')->get(); However, if you wanted to get only a specific column, you could pass it as an argument to the get() method.

What is all () in laravel?

all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.

Which method is used to fetch all records from the database in laravel?

After configuring the database, we can retrieve the records using the DB facade with select method.

What does get () do in laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.


2 Answers

The model attributes are populated by reading the data from the database. When using firstOrNew() and a record doesn't exist, it makes a new instance of the model object without reading from the database, so the only attributes it has will be the ones manually assigned. Additionally, since there is no record in the database yet, you can't just re-read the database to get the missing data.

In this case, you can use Schema::getColumnListing($tableName) to get an array of all the columns in the table. With that information, you can create a base array that has all the column names as keys, and null for all the values, and then merge in the values of your Drink object.

public function getDrinkData(Request $request)
{
    // firstOrNew will query using attributes, so no need for two queries
    $drink = Drink::firstOrNew(['shopId' => $request->session()->get('shopId')]);

    // if an existing record was found
    if($drink->exists) {
        $drink = $drink->attributesToArray();
    }
    // otherwise a new model instance was instantiated
    else {
        // get the column names for the table
        $columns = Schema::getColumnListing($drink->getTable());
        // create array where column names are keys, and values are null
        $columns = array_fill_keys($columns, null);

        // merge the populated values into the base array
        $drink = array_merge($columns, $drink->attributesToArray());
    }

    return view('shop.drink')->(['drink' => $drink])
}

If you were using firstOrCreate(), then a new record is created when one doesn't exist. Since there a record in the database now, you could simply re-read the record from the database to populated all of the model attributes. For example:

public function getDrinkData(Request $request)
{
    $drink = Drink::firstOrCreate(['shopId' => $request->session()->get('shopId')]);

    // If it was just created, refresh the model to get all the attributes.
    if ($drink->wasRecentlyCreated) {
        $drink = $drink->fresh();
    }

    return view('shop.drink')->(['drink' => $drink->attributesToArray()])
}
like image 52
patricus Avatar answered Oct 14 '22 10:10

patricus


What if you were to explicitly declare all the fields you want back.

An example of something I do that is a bit more basic as I'm not using where clauses and just getting all from Request object. I still think this could be helpful to someone out there.

public function getDrinkData(Request $request)
{
    // This will only give back the columns/attributes that have data.
    // NULL values will be omitted.
    //$drink = $request->all();

    // However by declaring all the attributes I want I can get back 
    // columns even if the value is null. Additional filtering can be 
    // added on if you still want/need to massage the data.
    $drink = $request->all([
        'id',
        'shopID',
        'name',
        'bottleID',
        'capacity'
    ]);

    //...

    return view('shop.drink')->(['drink' => $drink])
}
like image 39
Rockin4Life33 Avatar answered Oct 14 '22 11:10

Rockin4Life33